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

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

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

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

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

  return (
    <div className="flex flex-col gap-4">
      {/* Provider info */}
      <div className="flex items-center gap-2">
        <Badge variant="outline" className="capitalize">{agent.provider}</Badge>
        <span className="text-xs text-muted-foreground">Connected service</span>
      </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 items-center justify-between 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>
  );
}
