import sys
import requests
import re
import os
import json
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QCheckBox,
    QListWidget, QVBoxLayout, QHBoxLayout, QSystemTrayIcon, QMenu, QMessageBox,
    QMenuBar, QRadioButton, QButtonGroup, QDialog, QSpacerItem, QSizePolicy, QWidget
)
from PyQt6.QtGui import QIcon, QAction, QDesktopServices, QCursor
from PyQt6.QtCore import Qt, QUrl, QTimer

PROXY_FILE = 'D:\\ip_info\\settings\\proxies.json'
SETTINGS_FILE = 'D:\\ip_info\\settings\\settings.json'
ICON_PATH = 'D:\\ip_info\\icons\\app_ip.ico'

# Unified style for all buttons
BUTTON_STYLE = """
    QPushButton {
        border: none;
        background-color: #4CAF50;  /* Button color (soft green) */
        color: white;  /* Text color */
        padding: 10px 20px;
        border-radius: 5px;  /* Rounded corners */
    }
    QPushButton:hover {
        background-color: #45a049;  /* Button color on hover */
    }
"""

# New style for the Delete Proxy button (soft red)
BUTTON_STYLE_DELETE = """
    QPushButton {
        border: none;
        background-color: #f44336;  /* Soft red color */
        color: white;  /* Text color */
        padding: 10px 20px;
        border-radius: 5px;  /* Rounded corners */
    }
    QPushButton:hover {
        background-color: #da190b;  /* Darker red on hover */
    }
"""

def get_ip_and_isp(proxy_data=None, use_proxy=False, service_url='https://ipinfo.io/json'):
    try:
        proxies = None
        if use_proxy and proxy_data:
            protocol = proxy_data.get('protocol', 'socks5')
            server_port = proxy_data['server_port']
            username = proxy_data.get('username')
            password = proxy_data.get('password')
            proxy_url = f"{protocol}://{server_port}"
            if username and password:
                proxy_url = f"{protocol}://{username}:{password}@{server_port}"
            proxies = {
                'http': proxy_url,
                'https': proxy_url,
            }
        response = requests.get(service_url, proxies=proxies, timeout=10)
        data = response.json()
        
        if 'ipinfo.io' in service_url:
            ip = data.get('ip', 'N/A')
            org = data.get('org', 'N/A')
            city = data.get('city', 'N/A')
            country = data.get('country', 'N/A')

            # Extract ISP name without AS number
            if org.startswith('AS'):
                isp = ' '.join(org.split(' ')[1:])
            else:
                isp = org

        elif 'ipapi.co' in service_url:
            ip = data.get('ip', 'N/A')
            isp = data.get('org', 'N/A')
            city = data.get('city', 'N/A')
            country = data.get('country', 'N/A')

            # Extract ISP name without AS number
            if isp.startswith('AS'):
                isp = ' '.join(isp.split(' ')[1:])

        elif 'ip-api.com' in service_url:
            if data.get('status') != 'success':
                raise ValueError('API response status not success')
            ip = data.get('query', 'N/A')
            isp = data.get('isp', 'N/A')
            city = data.get('city', 'N/A')
            country = data.get('country', 'N/A')

        else:
            ip = 'N/A'
            isp = 'N/A'
            city = 'N/A'
            country = 'N/A'

        # Remove legal forms (case-insensitive and considering quotes)
        legal_forms = ['PJSC', 'LLC', 'JSC', 'OJSC', 'АО', 'ОАО', 'ЗАО', 'ООО', 'ПАО']
        pattern = r'\b(' + '|'.join(legal_forms) + r')\b'
        isp = re.sub(pattern, '', isp, flags=re.IGNORECASE).strip()

        # Remove extra characters like quotes or special symbols
        isp = isp.replace('"', '').replace('«', '').replace('»', '').strip()

        # Remove extra spaces
        isp = ' '.join(isp.split())

        return ip, isp, city, country
    except Exception as e:
        return 'Ошибка', 'Ошибка', 'Ошибка', 'Ошибка'

class AboutDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('О программе')
        self.setFixedSize(400, 200)
        self.setWindowIcon(parent.icon if parent and hasattr(parent, 'icon') else QIcon())

        layout = QVBoxLayout()

        # Title
        title_label = QLabel("JustWoofIP")
        title_font = title_label.font()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title_label)

        # Version
        version_label = QLabel("Версия: 1.0.0-20241101")
        version_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(version_label)

        # Website with link
        site_label = QLabel()
        site_label.setText(
            'Сайт: <a href="https://chat.mistral.ai" style="color: #1E90FF; font-weight: bold; text-decoration: none;">https://chat.mistral.ai</a>'
        )
        site_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        site_label.setOpenExternalLinks(False)  # Disable automatic link opening
        site_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
        site_label.linkActivated.connect(self.open_link)
        site_label.setStyleSheet("""
            QLabel {
                color: white;
                background-color: #1e1e1e;
            }
            a:hover {
                text-decoration: underline;
            }
        """)

        layout.addWidget(site_label)

        # Spacer for padding
        spacer = QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
        layout.addItem(spacer)

        # Close button
        close_button = QPushButton("Закрыть")
        close_button.clicked.connect(self.close)
        close_button.setStyleSheet(BUTTON_STYLE)
        close_button.setFixedWidth(100)
        close_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        layout.addWidget(close_button, alignment=Qt.AlignmentFlag.AlignCenter)

        self.setLayout(layout)
        self.setStyleSheet("background-color: #1e1e1e; color: white;")

    def open_link(self, link):
        QDesktopServices.openUrl(QUrl(link))
        self.close()

class MyApp(QMainWindow):
    def __init__(self):
        super().__init__()

        self.minimize_to_tray = False  # Default initialization

        self.initUI()

    def initUI(self):
        self.setWindowTitle('JustWoofIP')
        self.setStyleSheet("background-color: #1e1e1e; color: white;")

        # Set icon
        if os.path.exists(ICON_PATH):
            self.icon = QIcon(ICON_PATH)
            self.setWindowIcon(self.icon)
        else:
            self.icon = QIcon()

        # Create central widget and layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout()
        central_widget.setLayout(layout)

        # Menu Bar
        self.create_menu()

        # IP and Copy Button
        hbox_ip = QHBoxLayout()
        ip_label = QLabel("Мой IP:")
        self.ip_text = QLineEdit()
        self.ip_text.setReadOnly(True)
        self.ip_text.setStyleSheet("background-color: #323232; color: white;")
        hbox_ip.addWidget(ip_label)
        hbox_ip.addWidget(self.ip_text)

        # Copy Button next to IP
        self.copy_ip_button = QPushButton("Копировать")
        self.copy_ip_button.clicked.connect(self.copy_ip)
        self.copy_ip_button.setStyleSheet(BUTTON_STYLE)
        self.copy_ip_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        hbox_ip.addWidget(self.copy_ip_button)
        layout.addLayout(hbox_ip)

        # ISP, City, Country Fields
        hbox_isp = QHBoxLayout()
        isp_label = QLabel("Мой ISP:")
        self.isp_text = QLineEdit()
        self.isp_text.setReadOnly(True)
        self.isp_text.setStyleSheet("background-color: #323232; color: white;")
        hbox_isp.addWidget(isp_label)
        hbox_isp.addWidget(self.isp_text)

        # City
        city_label = QLabel("Город:")
        self.city_text = QLineEdit()
        self.city_text.setReadOnly(True)
        self.city_text.setStyleSheet("background-color: #323232; color: white;")
        hbox_isp.addWidget(city_label)
        hbox_isp.addWidget(self.city_text)

        # Country
        country_label = QLabel("Страна:")
        self.country_text = QLineEdit()
        self.country_text.setReadOnly(True)
        self.country_text.setStyleSheet("background-color: #323232; color: white;")
        hbox_isp.addWidget(country_label)
        hbox_isp.addWidget(self.country_text)

        layout.addLayout(hbox_isp)

        # Use Proxy checkbox and notification
        hbox_use_proxy = QHBoxLayout()
        self.use_proxy_checkbox = QCheckBox("Использовать прокси")
        self.use_proxy_checkbox.setChecked(False)  # Default: proxy not used
        hbox_use_proxy.addWidget(self.use_proxy_checkbox)

        # Notification Label
        self.notification_label = QLabel("", self)
        self.notification_label.setStyleSheet("""
            QLabel {
                background-color: rgba(50, 50, 50, 200);
                color: white;
                padding: 5px 10px;
                border-radius: 5px;
                font-weight: bold;
            }
        """)
        self.notification_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.notification_label.hide()

        # Add stretch and notification to the same row
        hbox_use_proxy.addStretch()
        hbox_use_proxy.addWidget(self.notification_label)
        layout.addLayout(hbox_use_proxy)

        # =======================
        # 1. Move "Добавить прокси" above proxy list
        # =======================
        # Add Proxy Input Field
        hbox4 = QHBoxLayout()
        new_proxy_label = QLabel("Добавить прокси:")
        self.new_proxy_text = QLineEdit()
        self.new_proxy_text.setStyleSheet("background-color: #323232; color: white;")
        hbox4.addWidget(new_proxy_label)
        hbox4.addWidget(self.new_proxy_text)
        layout.addLayout(hbox4)

        # =======================
        # 3. Make proxy list narrower (50%)
        # 4. Position Save and Delete buttons to the right
        # =======================
        hbox3 = QHBoxLayout()

        # Proxy List
        self.saved_proxy_choice = QListWidget()
        self.saved_proxy_choice.setStyleSheet("background-color: #323232; color: white;")
        # Set fixed width to 50% of the window width
        self.saved_proxy_choice.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        hbox3.addWidget(self.saved_proxy_choice, 1)  # Stretch factor 1

        # Vertical layout for buttons
        vbox_buttons = QVBoxLayout()

        # =======================
        # 2. Change "Delete Selected Proxy" button color to soft red
        # =======================
        # Save Proxy Button
        self.add_proxy_button = QPushButton("Сохранить прокси")
        self.add_proxy_button.setStyleSheet(BUTTON_STYLE)
        self.add_proxy_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.add_proxy_button.clicked.connect(self.on_add_proxy)

        # Delete Proxy Button with soft red color
        self.delete_proxy_button = QPushButton("Удалить выбранный прокси")
        self.delete_proxy_button.setStyleSheet(BUTTON_STYLE_DELETE)
        self.delete_proxy_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.delete_proxy_button.clicked.connect(self.on_delete_proxy)

        # Add buttons to the vertical layout with spacing
        vbox_buttons.addStretch()
        vbox_buttons.addWidget(self.add_proxy_button)
        vbox_buttons.addSpacing(10)  # Add spacing between buttons
        vbox_buttons.addWidget(self.delete_proxy_button)
        vbox_buttons.addStretch()

        # Add vertical button layout to the main horizontal layout
        hbox3.addLayout(vbox_buttons, 0)  # Stretch factor 0 to prevent stretching

        layout.addLayout(hbox3)

        # Service Selection with Additional ip-api.com
        hbox5 = QHBoxLayout()
        service_label = QLabel("Выбор сервиса:")
        self.service_group = QButtonGroup()
        self.ipinfo_radio = QRadioButton("ipinfo.io")
        self.ipapi_radio = QRadioButton("ipapi.co")
        self.ipapi_radio_new = QRadioButton("ip-api.com")  # New radio button
        self.service_group.addButton(self.ipinfo_radio)
        self.service_group.addButton(self.ipapi_radio)
        self.service_group.addButton(self.ipapi_radio_new)  # Add to group
        self.ipinfo_radio.setChecked(True)  # Default selection
        hbox5.addWidget(service_label)
        hbox5.addWidget(self.ipinfo_radio)
        hbox5.addWidget(self.ipapi_radio)
        hbox5.addWidget(self.ipapi_radio_new)  # Add to layout
        layout.addLayout(hbox5)

        # Get IP and ISP Button
        self.get_button = QPushButton("Получить IP и ISP")
        self.get_button.setStyleSheet(BUTTON_STYLE)
        self.get_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.get_button.clicked.connect(self.on_get_button)

        # Center the Get Button
        hbox_get = QHBoxLayout()
        hbox_get.addStretch()
        hbox_get.addWidget(self.get_button)
        hbox_get.addStretch()
        layout.addLayout(hbox_get)

        # Load saved proxies and settings
        self.load_saved_proxies()
        self.load_settings()

        # Create System Tray Icon
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.icon)
        self.tray_icon.setToolTip('JustWoofIP')
        self.tray_icon.activated.connect(self.on_tray_icon_activated)
        self.create_tray_menu()
        self.tray_icon.show()

    def create_menu(self):
        menubar = self.menuBar()

        # "Файл" Menu
        file_menu = menubar.addMenu('Файл')
        exit_action = QAction('Выход', self)
        exit_action.triggered.connect(self.on_menu_exit)
        file_menu.addAction(exit_action)

        # "Настройки" Menu
        settings_menu = menubar.addMenu('Настройки')
        minimize_to_tray_action = QAction('Сворачивать в трей при закрытии', self, checkable=True)
        minimize_to_tray_action.setChecked(self.minimize_to_tray)
        minimize_to_tray_action.triggered.connect(self.on_minimize_to_tray_toggled)
        settings_menu.addAction(minimize_to_tray_action)

        # "Справка" Menu
        help_menu = menubar.addMenu('Справка')
        about_action = QAction('О программе', self)
        about_action.triggered.connect(self.show_about_dialog)
        help_menu.addAction(about_action)

        # Set styles for the menu
        menubar.setStyleSheet("""
            QMenuBar {
                background-color: #323232;
                color: white;
            }
            QMenuBar::item:selected {
                background-color: #464646;
            }
            QMenu {
                background-color: #323232;
                color: white;
            }
            QMenu::item:selected {
                background-color: #464646;
            }
            QMenu::item:pressed {
                background-color: #5a5a5a;
            }
        """)

    def create_tray_menu(self):
        menu = QMenu()
        show_action = QAction("Показать", self)
        exit_action = QAction("Выход", self)
        show_action.triggered.connect(self.on_tray_show)
        exit_action.triggered.connect(self.on_tray_exit)
        menu.addAction(show_action)
        menu.addAction(exit_action)
        self.tray_icon.setContextMenu(menu)

    def on_tray_icon_activated(self, reason):
        if reason == QSystemTrayIcon.ActivationReason.Trigger:
            self.on_tray_show()

    def on_tray_show(self):
        self.showNormal()
        self.activateWindow()

    def on_tray_exit(self):
        self.tray_icon.hide()
        self.close()

    def on_menu_exit(self):
        self.tray_icon.hide()
        self.close()

    def on_minimize_to_tray_toggled(self, checked):
        self.minimize_to_tray = checked

    def closeEvent(self, event):
        self.save_settings()
        if self.minimize_to_tray:
            self.hide()
            event.ignore()
        else:
            self.tray_icon.hide()
            event.accept()

    def load_saved_proxies(self):
        self.saved_proxies = []
        if os.path.exists(PROXY_FILE):
            with open(PROXY_FILE, 'r', encoding='utf-8') as f:
                self.saved_proxies = json.load(f)
                self.update_saved_proxy_list()

    def save_proxies(self):
        os.makedirs(os.path.dirname(PROXY_FILE), exist_ok=True)  # Ensure directory exists
        with open(PROXY_FILE, 'w', encoding='utf-8') as f:
            json.dump(self.saved_proxies, f, ensure_ascii=False, indent=4)

    def update_saved_proxy_list(self):
        self.saved_proxy_choice.clear()
        for proxy in self.saved_proxies:
            display_text = f"{proxy['protocol']}://{proxy['server_port']}"
            if proxy.get('username') and proxy.get('password'):
                display_text += f" ({proxy['username']}:{proxy['password']})"
            self.saved_proxy_choice.addItem(display_text)

    def load_settings(self):
        if os.path.exists(SETTINGS_FILE):
            with open(SETTINGS_FILE, 'r', encoding='utf-8') as f:
                settings = json.load(f)
                use_proxy = settings.get('use_proxy', False)
                minimize_to_tray = settings.get('minimize_to_tray', False)
                selected_proxy_index = settings.get('selected_proxy_index', -1)
                selected_service = settings.get('selected_service', 'ipinfo.io')

                self.use_proxy_checkbox.setChecked(use_proxy)
                self.minimize_to_tray = minimize_to_tray
                if 0 <= selected_proxy_index < len(self.saved_proxies):
                    self.saved_proxy_choice.setCurrentRow(selected_proxy_index)
                if selected_service == 'ipinfo.io':
                    self.ipinfo_radio.setChecked(True)
                elif selected_service == 'ipapi.co':
                    self.ipapi_radio.setChecked(True)
                elif selected_service == 'ip-api.com':
                    self.ipapi_radio_new.setChecked(True)
        else:
            # If settings file doesn't exist, set default values
            self.use_proxy_checkbox.setChecked(False)
            self.minimize_to_tray = False
            self.ipinfo_radio.setChecked(True)

    def save_settings(self):
        selected_service = 'ipinfo.io'
        if self.ipinfo_radio.isChecked():
            selected_service = 'ipinfo.io'
        elif self.ipapi_radio.isChecked():
            selected_service = 'ipapi.co'
        elif self.ipapi_radio_new.isChecked():
            selected_service = 'ip-api.com'

        settings = {
            'use_proxy': self.use_proxy_checkbox.isChecked(),
            'minimize_to_tray': self.minimize_to_tray,
            'selected_proxy_index': self.saved_proxy_choice.currentRow(),
            'selected_service': selected_service
        }
        os.makedirs(os.path.dirname(SETTINGS_FILE), exist_ok=True)  # Ensure directory exists
        with open(SETTINGS_FILE, 'w', encoding='utf-8') as f:
            json.dump(settings, f, ensure_ascii=False, indent=4)

    def on_get_button(self):
        use_proxy = self.use_proxy_checkbox.isChecked()
        if self.ipinfo_radio.isChecked():
            service_url = 'https://ipinfo.io/json'
        elif self.ipapi_radio.isChecked():
            service_url = 'https://ipapi.co/json/'
        elif self.ipapi_radio_new.isChecked():
            service_url = 'http://ip-api.com/json/'
        else:
            service_url = 'https://ipinfo.io/json'  # Default

        proxy_data = None
        if use_proxy:
            selected_index = self.saved_proxy_choice.currentRow()
            if selected_index != -1 and selected_index < len(self.saved_proxies):
                # User selected proxy manually
                proxy_data = self.saved_proxies[selected_index]
            elif len(self.saved_proxies) > 0:
                # User didn't select a proxy manually, apply the first one
                proxy_data = self.saved_proxies[0]

        ip, isp, city, country = get_ip_and_isp(proxy_data, use_proxy, service_url)
        self.ip_text.setText(ip)
        self.isp_text.setText(isp)
        self.city_text.setText(city)
        self.country_text.setText(country)

    def on_add_proxy(self):
        proxy_input = self.new_proxy_text.text().strip()
        if proxy_input:
            # Expected format: protocol://server:port (username:password)
            parts = proxy_input.split()
            if len(parts) == 1 or len(parts) == 2:
                proxy_url = parts[0]
                auth = parts[1] if len(parts) == 2 else ''
                if '://' in proxy_url:
                    try:
                        protocol, server_port = proxy_url.split('://', 1)
                    except ValueError:
                        self.show_notification_inline("Некорректный формат прокси", duration=1000)
                        return
                else:
                    protocol = 'socks5'  # Default
                    server_port = proxy_url

                proxy_data = {'protocol': protocol, 'server_port': server_port}
                if auth:
                    if ':' in auth:
                        username, password = auth.split(':', 1)
                        proxy_data['username'] = username
                        proxy_data['password'] = password
                    else:
                        proxy_data['username'] = auth
                        proxy_data['password'] = ''

                # Add the proxy to the list and save
                self.saved_proxies.append(proxy_data)
                self.save_proxies()
                self.update_saved_proxy_list()
                self.new_proxy_text.clear()
                self.show_notification_inline("Прокси сохранен", duration=1000)
            else:
                self.show_notification_inline("Некорректный формат ввода прокси", duration=1000)
        else:
            self.show_notification_inline("Поле для ввода прокси пустое", duration=1000)

    def on_delete_proxy(self):
        selected_index = self.saved_proxy_choice.currentRow()
        if selected_index != -1:
            del self.saved_proxies[selected_index]
            self.save_proxies()
            self.update_saved_proxy_list()
            self.show_notification_inline("Прокси удален", duration=1000)
        else:
            self.show_notification_inline("Не выбран прокси для удаления", duration=1000)

    def copy_ip(self):
        ip = self.ip_text.text().strip()
        if ip and ip != 'N/A' and ip != 'Ошибка':
            clipboard = QApplication.clipboard()
            clipboard.setText(ip)
            self.show_notification_inline("IP-адрес скопирован", duration=1000)
        else:
            self.show_notification_inline("Нечего копировать", duration=1000)

    def show_notification_inline(self, message, duration=1000):
        """Show notification in the designated space next to the proxy checkbox."""
        self.notification_label.setText(message)
        self.notification_label.adjustSize()
        self.notification_label.setFixedHeight(30)
        # Center the notification in the available space
        self.notification_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.notification_label.show()

        # Create a timer to hide the notification after `duration` milliseconds
        QTimer.singleShot(duration, self.notification_label.hide)

    def show_about_dialog(self):
        dialog = AboutDialog(self)
        dialog.exec()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    ex.show()
    sys.exit(app.exec())