import { useState, useEffect, useMemo } from 'react';
import { toast } from 'sonner';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useSettings } from '@/state/useSettings';
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';

export const TaskDefaults = () => {
  const { settings, saveSettings } = useSettings();
  const claudeModels = useVisibleClaudeModels();
  const openCodeModels = useVisibleOpenCodeModels();
  const [isSaving, setIsSaving] = useState(false);

  const [model, setModel] = useState<string | null>(settings.tasks.defaultModel);

  useEffect(() => {
    setModel(settings.tasks.defaultModel);
  }, [settings]);

  const openCodeGroups = useMemo(() => {
    const groups: Record<string, { id: string; name: string }[]> = {};
    for (const m of openCodeModels) {
      const provider = m.provider ?? 'OpenCode';
      if (!groups[provider]) groups[provider] = [];
      groups[provider].push({ id: m.id, name: m.name });
    }
    return Object.entries(groups)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([provider, models]) => ({ provider, models: models.sort((a, b) => a.name.localeCompare(b.name)) }));
  }, [openCodeModels]);

  const handleSave = async () => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      const isOpenCode = openCodeModels.some((m) => m.id === model);
      const defaultProvider = isOpenCode ? ('opencode' as const) : ('claude' as const);
      await saveSettings({ ...settings, tasks: { defaultProvider, defaultModel: model } });
      toast.success('Task defaults saved');
    } catch {
      toast.error('Failed to save settings');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="grid gap-4">
      <Label className="grid gap-2">
        <span className="text-duck-dark/70">Default Model</span>
        <Select value={model ?? ''} onValueChange={(v) => setModel(v || null)}>
          <SelectTrigger className="h-11 bg-white/60 border-duck-dark/20 text-duck-dark">
            <SelectValue placeholder="Same as chat default" />
          </SelectTrigger>
          <SelectContent className="z-[600] max-h-[300px]">
            {claudeModels.length > 0 && (
              <SelectGroup>
                <SelectLabel>Claude</SelectLabel>
                {claudeModels.map((m) => (
                  <SelectItem key={m.id} value={m.id}>
                    {m.name}
                  </SelectItem>
                ))}
              </SelectGroup>
            )}
            {openCodeGroups.map(({ provider, models }) => (
              <SelectGroup key={provider}>
                <SelectLabel>{provider} (OpenCode)</SelectLabel>
                {models.map((m) => (
                  <SelectItem key={`${provider}:${m.id}`} value={m.id}>
                    {m.name}
                  </SelectItem>
                ))}
              </SelectGroup>
            ))}
          </SelectContent>
        </Select>
      </Label>

      <Button
        type="button"
        onClick={handleSave}
        disabled={isSaving}
        className="w-full 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>
    </div>
  );
};
