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 { useUserVisibleModels, type ModelOption } from 'state/useModels';

export const TaskDefaults = () => {
  const { settings, saveSettings } = useSettings();
  const models = useUserVisibleModels();
  const [isSaving, setIsSaving] = useState(false);

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

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

  const buildGroups = (models: ModelOption[], fallback: string) => {
    const groups: Record<string, { id: string; name: string }[]> = {};
    for (const m of models) {
      const provider = m.provider ?? fallback;
      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)) }));
  };

  const modelGroups = useMemo(() => buildGroups(models, 'Chat'), [models]);

  const handleSave = async () => {
    if (isSaving) return;
    setIsSaving(true);
    try {
      await saveSettings({ ...settings, tasks: { defaultProvider: 'chat', 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-background/60 border-duck-dark/20 text-duck-dark">
            <SelectValue placeholder="Same as chat default" />
          </SelectTrigger>
          <SelectContent className="z-[600] max-h-[300px]">
            {modelGroups.map(({ provider, models }) => (
              <SelectGroup key={`pi-${provider}`}>
                <SelectLabel>{provider}</SelectLabel>
                {models.map((m) => (
                  <SelectItem key={`pi:${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>
  );
};
