import os
from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton,
    QMessageBox, QHBoxLayout, QToolButton
)
from PyQt5.QtGui import QIcon, QDesktopServices
from PyQt5.QtCore import QSize, pyqtSignal, QUrl
from config import BASE_DIR, t, reload_keys
from dotenv import dotenv_values
from utils.path_utils import resource_path


class SettingsWindow(QWidget):
    keys_updated = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.setWindowTitle(t("api_settings_title"))
        self.resize(400, 300)

        self.inputs = {}
        self.labels = {}
        self.globe_buttons = {}

        self.env_path = os.path.join(BASE_DIR, ".env")
        current_env = dotenv_values(self.env_path)

        layout = QVBoxLayout(self)

        self.keys = [
            "OPENAI_API_KEY",
            "MISTRAL_API_KEY",
            "GEMINI_API_KEY",
            "DEEPSEEK_API_KEY",
            "GROK_API_KEY",
            "OPENROUTER_API_KEY"
        ]
        self.url_map = {
            "OPENAI_API_KEY": "https://platform.openai.com/api-keys",
            "MISTRAL_API_KEY": "https://console.mistral.ai/api-keys",
            "GEMINI_API_KEY": "https://aistudio.google.com/app/apikey",
            "DEEPSEEK_API_KEY": "https://platform.deepseek.com/api_keys",
            "GROK_API_KEY": "https://x.ai/api",
            "OPENROUTER_API_KEY": "https://openrouter.ai/keys"
        }

        for key in self.keys:
            label = QLabel(self.format_key_label(key))
            layout.addWidget(label)
            self.labels[key] = label

            row = QHBoxLayout()
            inp = QLineEdit()
            inp.setText(current_env.get(key, ""))
            inp.setPlaceholderText(f"{key}…")
            inp.setEchoMode(QLineEdit.Password)
            row.addWidget(inp)

            btn_eye = QToolButton()
            btn_eye.setIcon(QIcon(resource_path("assets/icons/eye.png")))
            btn_eye.setCheckable(True)
            btn_eye.setChecked(False)
            btn_eye.setToolTip(t("toggle_visibility"))
            btn_eye.setIconSize(QSize(16, 16))
            btn_eye.setFixedSize(24, 24)
            btn_eye.clicked.connect(lambda _, i=inp, b=btn_eye: self.toggle_visibility(i, b))
            row.addWidget(btn_eye)

            btn_globe = QToolButton()
            btn_globe.setIcon(QIcon(resource_path("assets/icons/globe icon.png")))
            btn_globe.setToolTip(t("tooltip_open_api_page"))
            btn_globe.setIconSize(QSize(16, 16))
            btn_globe.setFixedSize(24, 24)
            btn_globe.clicked.connect(lambda _, url=self.url_map[key]: QDesktopServices.openUrl(QUrl(url)))
            row.addWidget(btn_globe)

            self.inputs[key] = inp
            self.globe_buttons[key] = btn_globe
            layout.addLayout(row)

        # Кнопка сохранения
        self.btn_save = QPushButton(t("btn_save_settings"), self)
        self.btn_save.clicked.connect(self.save_env)
        layout.addWidget(self.btn_save)

    def format_key_label(self, key: str) -> str:
        # "OPENAI_API_KEY" → "OpenAI API Key"
        parts = key.replace("_KEY", "").split("_")
        return " ".join(p.capitalize() if p != "API" else "API" for p in parts)

    def toggle_visibility(self, line_edit: QLineEdit, btn: QToolButton):
        if line_edit.echoMode() == QLineEdit.Password:
            line_edit.setEchoMode(QLineEdit.Normal)
            btn.setIcon(QIcon(resource_path("assets/icons/eye_off.png")))
        else:
            line_edit.setEchoMode(QLineEdit.Password)
            btn.setIcon(QIcon(resource_path("assets/icons/eye.png")))

    def save_env(self):
        env_data = {key: field.text().strip() for key, field in self.inputs.items()}
        try:
            with open(self.env_path, "w", encoding="utf-8") as f:
                for key, value in env_data.items():
                    f.write(f"{key}={value}\n")

            reload_keys()
            QMessageBox.information(self, t("success_title"), t("keys_saved"))
            self.keys_updated.emit()
            self.close()
        except Exception as e:
            QMessageBox.critical(self, t("error_title"), f"{t('error_cannot_save_file')}: {e}")

    def retranslate_ui(self):
        self.setWindowTitle(t("api_settings_title"))
        for key in self.keys:
            if key in self.labels:
                self.labels[key].setText(self.format_key_label(key))
            if key in self.globe_buttons:
                self.globe_buttons[key].setToolTip(t("tooltip_open_api_page"))
        self.btn_save.setText(t("btn_save_settings"))
