import { useState } from 'react';
import { Bot, Plus } from 'lucide-react';
import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';
import { Button } from '@/components/ui/button';
import type { CloudAgentConfig } from '../../../../shared/api-types';
import type { LocalAgentConfig } from './types';
import { AgentRow } from './AgentRow';
import { InlineAgentCreationStepper } from './InlineAgentCreationStepper';
import { JourneyDialog } from './JourneyDialog';
import { useTranslation } from 'react-i18next';

export function AgentsSection() {
  const { t } = useTranslation();
  const utils = trpc.useUtils();
  const localAgentsQuery = trpc.agent.local.list.useQuery();
  const cloudAgentsQuery = trpc.agent.cloud.list.useQuery();
  const deleteLocalMutation = trpc.agent.local.delete.useMutation();
  const deleteCloudMutation = trpc.agent.cloud.delete.useMutation();
  const updateLocalMutation = trpc.agent.local.update.useMutation();
  const updateCloudMutation = trpc.agent.cloud.update.useMutation();
  const runNowMutation = trpc.agent.runNow.useMutation();

  const { notify, notifyError, notifyPromise } = useNotify();
  const [expandedAgent, setExpandedAgent] = useState<string | null>(null);
  const [showTemplatePicker, setShowTemplatePicker] = useState(false);
  const [journeyAgent, setJourneyAgent] = useState<{ id: string; type: 'local' | 'cloud'; name: string; currentConfig: Record<string, unknown> | null; dataTypes: string[]; directory?: string } | null>(null);

  const catalogQuery = trpc.agent.catalog.useQuery(undefined, {
    enabled: showTemplatePicker,
  });

  const localAgents: LocalAgentConfig[] = localAgentsQuery.data ?? [];
  const cloudAgents: CloudAgentConfig[] = cloudAgentsQuery.data ?? [];
  const allAgents = [
    ...localAgents.map(a => ({ ...a, agentType: 'local' as const })),
    ...cloudAgents.map(a => ({ ...a, agentType: 'cloud' as const })),
  ];
  const hasAgents = allAgents.length > 0;

  function handleDelete(id: string, type: 'local' | 'cloud') {
    const mutation = type === 'local' ? deleteLocalMutation : deleteCloudMutation;
    mutation.mutate({ id }, {
      onSuccess: () => {
        notify('warning', 'toast.agent.deleted');
        void utils.agent.local.list.invalidate();
        void utils.agent.cloud.list.invalidate();
      },
      onError: (err) => notifyError('toast.agent.deleteError', err),
    });
  }

  function handleToggleEnabled(id: string, type: 'local' | 'cloud', enabled: boolean) {
    if (type === 'local') {
      updateLocalMutation.mutate({ id, enabled }, {
        onSuccess: () => void utils.agent.local.list.invalidate(),
        onError: (err) => notifyError('toast.agent.updateError', err),
      });
    } else {
      updateCloudMutation.mutate({ id, enabled }, {
        onSuccess: () => void utils.agent.cloud.list.invalidate(),
        onError: (err) => notifyError('toast.agent.updateError', err),
      });
    }
  }

  function handleRunNow(id: string) {
    const promise = runNowMutation.mutateAsync({ id });
    notifyPromise(promise, { loading: 'toast.agent.runStarted', success: 'toast.agent.runStarted', error: 'toast.agent.runError' });
  }

  return (
    <div className="flex flex-col gap-8">
      {/* Empty first-run state */}
      {!hasAgents && !showTemplatePicker && (
        <div className="py-4 text-center">
          <div className="size-11 rounded-2xl bg-primary/10 flex items-center justify-center mx-auto mb-4">
            <Bot className="size-5 text-primary" />
          </div>
          <h2 className="text-base font-semibold">{t('agents.noAgentsYet')}</h2>
          <p className="text-sm text-muted-foreground max-w-md mx-auto mt-1.5">
            {t('agents.noAgentsDescription')}
          </p>
          <Button size="sm" className="mt-5" onClick={() => setShowTemplatePicker(true)}>
            <Plus className="size-3.5 mr-1.5" />
            {t('agents.createFirstAgent')}
          </Button>
        </div>
      )}

      {/* Existing configured agents */}
      {hasAgents && !showTemplatePicker && (
        <div className="flex flex-col gap-3">
          <div className="flex items-center justify-between gap-3">
            <h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">{t('agents.yourAgents')}</h2>
            <Button size="sm" variant="outline" onClick={() => setShowTemplatePicker(prev => !prev)}>
              <Plus className="size-3.5 mr-1.5" />
              {t('agents.createAgent')}
            </Button>
          </div>
          <div className="grid gap-4 md:grid-cols-2">
            {allAgents.map((agent) => (
              <AgentRow
                key={agent.id}
                agent={agent}
                expanded={expandedAgent === agent.id}
                onToggleExpand={() => setExpandedAgent(prev => prev === agent.id ? null : agent.id)}
                onToggleEnabled={(enabled) => handleToggleEnabled(agent.id, agent.agentType, enabled)}
                onDelete={() => handleDelete(agent.id, agent.agentType)}
                onRunNow={() => handleRunNow(agent.id)}
                onOpenJourney={() => setJourneyAgent({
                  id: agent.id,
                  type: agent.agentType,
                  name: agent.name,
                  currentConfig: agent.agentType === 'local' ? (agent as LocalAgentConfig).agentConfig ?? null : null,
                  dataTypes: agent.dataTypes,
                  directory: agent.agentType === 'local' ? (agent as LocalAgentConfig).directory : undefined,
                })}
              />
            ))}
          </div>
        </div>
      )}

      {/* Backend templates picker */}
      {showTemplatePicker && (
        <InlineAgentCreationStepper
          catalog={catalogQuery.data ?? []}
          isLoadingCatalog={catalogQuery.isPending}
          onCancel={() => setShowTemplatePicker(false)}
          onCreated={() => {
            setShowTemplatePicker(false);
            void utils.agent.local.list.invalidate();
            void utils.agent.cloud.list.invalidate();
          }}
        />
      )}

      {/* Chatbot Journey dialog */}
      {journeyAgent && (
        <JourneyDialog
          agentType={journeyAgent.type}
          agentName={journeyAgent.name}
          currentConfig={journeyAgent.currentConfig}
          dataTypes={journeyAgent.dataTypes}
          directory={journeyAgent.directory}
          onClose={() => setJourneyAgent(null)}
          onSaved={(agentConfig) => {
            const local = localAgents.find(a => a.id === journeyAgent.id);
            if (local) {
              updateLocalMutation.mutate({ id: journeyAgent.id, agentConfig }, {
                onSuccess: () => {
                  void utils.agent.local.list.invalidate();
                  setJourneyAgent(null);
                },
              });
            } else {
              setJourneyAgent(null);
            }
          }}
        />
      )}
    </div>
  );
}
