import { useState } from 'react';
import { FolderOpen, X, Sparkles } from 'lucide-react';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { LocalAgentConfig } from './types';
import { DATA_TYPES, SCHEDULE_OPTIONS } from './types';

export function LocalAgentConfigPanel({
  agent,
  onOpenJourney,
}: {
  agent: LocalAgentConfig & { agentType: 'local' };
  onOpenJourney: () => void;
}) {
  const utils = trpc.useUtils();
  const updateMutation = trpc.agent.local.update.useMutation();

  const [directory, setDirectory] = useState(agent.directory ?? '');
  const [dataTypes, setDataTypes] = useState<string[]>(agent.dataTypes ?? []);
  const [schedule, setSchedule] = useState(agent.scheduleCron ?? '0 * * * *');
  const { notify, notifyError } = useNotify();

  async function pickDirectory() {
    try {
      const result = await window.electronDialog.showOpenDialog({
        properties: ['openDirectory'],
        title: 'Select directory for agent to watch',
      });
      if (!result.canceled && result.filePaths.length > 0) {
        setDirectory(result.filePaths[0]!);
      }
    } catch {
      // dialog not available (probably outside Electron)
    }
  }

  function toggleDataType(type: string) {
    setDataTypes(prev =>
      prev.includes(type) ? prev.filter(t => t !== type) : [...prev, type],
    );
  }

  function handleSave() {
    updateMutation.mutate(
      { id: agent.id, directory, dataTypes, scheduleCron: schedule },
      {
        onSuccess: () => {
          notify('success', 'toast.agent.updated');
          void utils.agent.local.list.invalidate();
        },
        onError: (err) => notifyError('toast.agent.updateError', err),
      },
    );
  }

  return (
    <div className="flex flex-col gap-4">
      {/* Directory */}
      <div>
        <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide block mb-2">Directory</label>
        {directory && (
          <div className="flex items-center gap-2 bg-muted/40 rounded-md px-3 py-1.5 text-xs font-mono mb-2">
            <FolderOpen className="size-3 text-muted-foreground shrink-0" />
            <span className="flex-1 truncate">{directory}</span>
            <button onClick={() => setDirectory('')} className="text-muted-foreground hover:text-foreground">
              <X className="size-3" />
            </button>
          </div>
        )}
        <Button size="sm" variant="outline" onClick={pickDirectory}>
          <FolderOpen className="size-3.5 mr-1.5" />
          {directory ? 'Change directory' : 'Select directory'}
        </Button>
      </div>

      {/* Data types */}
      <div>
        <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide block mb-2">What to extract</label>
        <div className="flex flex-wrap gap-4">
          {DATA_TYPES.map(type => (
            <label key={type} className="flex items-center gap-2 text-sm cursor-pointer">
              <Checkbox
                checked={dataTypes.includes(type)}
                onCheckedChange={() => toggleDataType(type)}
              />
              <span className="capitalize">{type}</span>
            </label>
          ))}
        </div>
      </div>

      {/* Schedule */}
      <div>
        <label className="text-xs font-medium text-muted-foreground uppercase tracking-wide block mb-2">Schedule</label>
        <Select value={schedule} onValueChange={setSchedule}>
          <SelectTrigger className="w-full">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {SCHEDULE_OPTIONS.map(opt => (
              <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* AI Prompt + Save */}
      <div className="flex flex-wrap items-center justify-between gap-2 pt-1">
        <Button size="sm" variant="outline" onClick={onOpenJourney}>
          <Sparkles className="size-3.5 mr-1.5" />
          Customize AI prompt
        </Button>
        <Button size="sm" onClick={handleSave} disabled={updateMutation.isPending}>
          Save changes
        </Button>
      </div>
    </div>
  );
}
