import { useState, useEffect } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useClient } from 'hooks/useClient';

type SttConfig = {
  url: string;
};

export const STTSection = () => {
  const client = useClient();
  const queryClient = useQueryClient();

  const { data: config, isLoading } = useQuery({
    queryKey: ['STT_CONFIG'],
    queryFn: () => client.get<SttConfig | null>('/server-settings/stt'),
  });

  const [url, setUrl] = useState('http://localhost:64201');
  const [isSaving, setIsSaving] = useState(false);
  const [isTesting, setIsTesting] = useState(false);

  useEffect(() => {
    if (!config) return;
    setUrl(config.url);
  }, [config]);

  const handleSave = async () => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      await client.put('/server-settings/stt', { url });
      queryClient.invalidateQueries({ queryKey: ['STT_CONFIG'] });
      toast.success('STT settings saved');
    } catch {
      toast.error('Failed to save STT settings');
    } finally {
      setIsSaving(false);
    }
  };

  const handleTest = async () => {
    if (isTesting) return;
    setIsTesting(true);
    try {
      const res = await client.post<{ success?: boolean; error?: string }>('/server-settings/stt/test', { url });
      if (res.error) {
        toast.error(res.error);
      } else {
        toast.success('Whisper server is reachable');
      }
    } catch (err: unknown) {
      const raw = (err as { message?: string })?.message;
      let msg = 'Connection failed';
      try {
        if (raw) msg = JSON.parse(raw).error ?? msg;
      } catch {
        /* ignore */
      }
      toast.error(msg);
    } finally {
      setIsTesting(false);
    }
  };

  if (isLoading) return <p className="text-sm text-duck-dark/40">Loading...</p>;

  return (
    <div className="grid gap-4">
      <Label className="grid gap-2">
        <span className="text-duck-dark/70 dark:text-foreground/70">Whisper Server URL</span>
        <Input
          className="h-11 bg-background/60 border-duck-dark/20 text-duck-dark dark:text-foreground placeholder:text-duck-dark/40"
          placeholder="http://localhost:64201"
          value={url}
          onChange={(ev) => setUrl(ev.target.value)}
        />
      </Label>

      <div className="flex items-center gap-2">
        <Button
          type="button"
          onClick={handleSave}
          disabled={isSaving}
          className="flex-1 h-11 bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold transition-all duration-200 hover:scale-105 cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
        >
          {isSaving ? 'Saving...' : 'Save'}
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={handleTest}
          disabled={isTesting}
          className="h-11 cursor-pointer disabled:opacity-50"
        >
          {isTesting ? 'Testing...' : 'Test'}
        </Button>
      </div>
    </div>
  );
};
