import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useSettings } from "@/hooks/useSettings";
import { testConnection } from "@/services/llm";
import { Loader2, CheckCircle2, XCircle } from "lucide-react";
import type { Settings } from "@/lib/types";

interface Props {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function SettingsDialog({ open, onOpenChange }: Props) {
  const { settings, updateSettings } = useSettings();
  const [apiKey, setApiKey] = useState(settings.apiKey ?? "");
  const [provider, setProvider] = useState<Settings["llmProvider"]>(
    settings.llmProvider,
  );
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<{
    success: boolean;
    message: string;
  } | null>(null);

  // Sync local state when dialog opens
  useEffect(() => {
    if (open) {
      setApiKey(settings.apiKey ?? "");
      setProvider(settings.llmProvider);
      setTestResult(null);
    }
  }, [open, settings.apiKey, settings.llmProvider]);

  const handleTest = async () => {
    setTesting(true);
    setTestResult(null);

    // Temporarily save to test
    await updateSettings({ llmProvider: provider, apiKey: apiKey || null });

    try {
      const message = await testConnection();
      setTestResult({ success: true, message });
    } catch (e) {
      setTestResult({
        success: false,
        message: e instanceof Error ? e.message : String(e),
      });
    } finally {
      setTesting(false);
    }
  };

  const handleSave = async () => {
    await updateSettings({ llmProvider: provider, apiKey: apiKey || null });
    onOpenChange(false);
  };

  const handleCancel = () => {
    // Reset to current settings
    setApiKey(settings.apiKey ?? "");
    setProvider(settings.llmProvider);
    setTestResult(null);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Settings</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="provider">LLM Provider</Label>
            <Select
              value={provider}
              onValueChange={(v) => setProvider(v as Settings["llmProvider"])}
            >
              <SelectTrigger id="provider">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="anthropic">Anthropic (Claude)</SelectItem>
                <SelectItem value="groq">Groq</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="apiKey">API Key</Label>
            <Input
              id="apiKey"
              type="password"
              value={apiKey}
              onChange={(e) => setApiKey(e.target.value)}
              placeholder="Enter your API key"
            />
            <p className="text-xs text-muted-foreground">
              {provider === "anthropic"
                ? "Get your key at console.anthropic.com"
                : "Get your key at console.groq.com"}
            </p>
          </div>

          <Button
            onClick={handleTest}
            disabled={!apiKey || testing}
            variant="outline"
            className="w-full"
          >
            {testing ? (
              <Loader2 className="size-4 animate-spin" />
            ) : (
              "Test Connection"
            )}
          </Button>

          {testResult && (
            <div
              className={`flex items-center gap-2 text-sm ${testResult.success ? "text-green-600" : "text-destructive"}`}
            >
              {testResult.success ? (
                <CheckCircle2 className="size-4" />
              ) : (
                <XCircle className="size-4" />
              )}
              {testResult.message}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={handleCancel}>
            Cancel
          </Button>
          <Button onClick={handleSave}>Save</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
