import { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { notifications } from '@mantine/notifications';
import { useTranslation } from 'react-i18next';
import { IconCheck, IconAlertCircle, IconPlugConnectedX } from '@tabler/icons-react';
import React from 'react';

interface SandboxConfig {
  enabled: boolean;
  api_url: string | null;
  api_key: string | null;
  snapshot: string | null;
}

interface ToolProvider {
  id: string;
  is_available: boolean;
}

export function useSandboxSettings() {
  const { t } = useTranslation();
  const [apiUrl, setApiUrl] = useState('https://app.daytona.io');
  const [apiKey, setApiKey] = useState('');
  const [snapshot, setSnapshot] = useState('');
  const [testing, setTesting] = useState(false);
  const [disabling, setDisabling] = useState(false);
  const [creatingSnapshot, setCreatingSnapshot] = useState(false);
  const [isAvailable, setIsAvailable] = useState(false);
  const [activeTab, setActiveTab] = useState<string>('config');

  useEffect(() => {
    loadAll();
  }, []);

  const loadAll = async () => {
    try {
      const [config, providers] = await Promise.all([
        invoke<SandboxConfig | null>('get_app_config', { key: 'sandbox' }),
        invoke<ToolProvider[]>('list_tool_providers'),
      ]);
      if (config) {
        if (config.api_url) setApiUrl(config.api_url);
        if (config.api_key) setApiKey(config.api_key);
        if (config.snapshot) setSnapshot(config.snapshot);
      }
      const sandboxProvider = providers.find((p) => p.id === 'sandbox');
      setIsAvailable(sandboxProvider?.is_available ?? false);
    } catch (e) {
      console.error('Failed to load sandbox config:', e);
    }
  };

  const saveConfig = async (overrides?: Partial<SandboxConfig>) => {
    await invoke('set_app_config', {
      key: 'sandbox',
      value: {
        enabled: isAvailable,
        api_url: apiUrl.trim(),
        api_key: apiKey.trim(),
        snapshot: snapshot.trim() || null,
        ...overrides,
      },
    });
  };

  const handleTestConnection = async () => {
    if (!apiUrl.trim() || !apiKey.trim()) {
      notifications.show({
        title: t('common.failed'),
        message: t('settings.sandbox.testMissingFields'),
        color: 'yellow',
      });
      return;
    }

    setTesting(true);
    try {
      await saveConfig({ enabled: true });
      await invoke<string>('test_sandbox_connection', {
        apiUrl: apiUrl.trim(),
        apiKey: apiKey.trim(),
      });
      setIsAvailable(true);
      notifications.show({
        title: t('settings.sandbox.testOkAutoEnabled'),
        message: t('settings.sandbox.testOkMsg'),
        color: 'teal',
        icon: React.createElement(IconCheck, { size: 18 }),
      });
    } catch (e) {
      setIsAvailable(false);
      await saveConfig({ enabled: false }).catch(() => {});
      notifications.show({
        title: t('settings.sandbox.testFailed'),
        message: t('settings.sandbox.testFailedMsg', { error: String(e) }),
        color: 'red',
        icon: React.createElement(IconAlertCircle, { size: 18 }),
      });
    } finally {
      setTesting(false);
    }
  };

  const handleDisable = async () => {
    setDisabling(true);
    try {
      await saveConfig({ enabled: false });
      setIsAvailable(false);
      setActiveTab('config');
      notifications.show({
        title: t('settings.sandbox.disableSuccess'),
        message: t('settings.sandbox.disableSuccessMsg'),
        color: 'orange',
        icon: React.createElement(IconPlugConnectedX, { size: 18 }),
      });
    } catch (e) {
      notifications.show({
        title: t('settings.sandbox.saveFailed'),
        message: String(e),
        color: 'red',
        icon: React.createElement(IconAlertCircle, { size: 18 }),
      });
    } finally {
      setDisabling(false);
    }
  };

  const handleCreateSnapshot = async (snapName: string) => {
    setCreatingSnapshot(true);
    try {
      await saveConfig();
    } catch {
      /* ignore */
    }

    try {
      await invoke<string>('create_playwright_snapshot', { snapshotName: snapName });
      setSnapshot(snapName);
      await saveConfig({ snapshot: snapName });
      notifications.show({
        title: t('settings.sandbox.snapshotDone'),
        message: t('settings.sandbox.snapshotDoneMsg', { name: snapName }),
        color: 'teal',
        icon: React.createElement(IconCheck, { size: 18 }),
        autoClose: 8000,
      });
    } catch (e) {
      notifications.show({
        title: t('settings.sandbox.snapshotFailed'),
        message: String(e),
        color: 'red',
        icon: React.createElement(IconAlertCircle, { size: 18 }),
        autoClose: 10000,
      });
    } finally {
      setCreatingSnapshot(false);
    }
  };

  const handleSetDefaultSnapshot = async (name: string) => {
    setSnapshot(name);
    try {
      await saveConfig({ snapshot: name });
      notifications.show({
        title: t('common.success'),
        message: t('settings.sandbox.saveDefaultSuccess'),
        color: 'teal',
        icon: React.createElement(IconCheck, { size: 18 }),
      });
    } catch (e) {
      notifications.show({
        title: t('common.failed'),
        message: String(e),
        color: 'red',
      });
    }
  };

  return {
    apiUrl, setApiUrl,
    apiKey, setApiKey,
    snapshot,
    testing,
    disabling,
    creatingSnapshot,
    isAvailable,
    activeTab, setActiveTab,
    handleTestConnection,
    handleDisable,
    handleCreateSnapshot,
    handleSetDefaultSnapshot,
  };
}
