'use client';

import { useState, useEffect, useCallback } from 'react';
import { Plus, Bot, Search } from 'lucide-react';
import { listAgents, updateAgent, deleteAgent } from '@client/api/ai-agents';
import type { AiAgent } from '@client/api/ai-agents';
import { useAuth } from '@client/contexts/AuthContext';
import { toast } from 'sonner';
import { InlineFormSkeleton } from '@client/components/skeletons/PageSkeletons';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import AgentCard from './AgentCard';
import AgentDrawer from './AgentDrawer';
import AgentPreview from './AgentPreview';
import FeatureGuard from '@client/components/FeatureGuard';
import { isFeatureLockedError } from '@client/utils/isFeatureLockedError';

export default function AIAgentConfigPage() {
  const { t } = useLanguage();
  usePageHeader(t('nav.aiConfiguration', 'AI Agents'), t('nav.aiAgentsSubtitle', 'Create and manage your AI agents'));
  const { restaurantId } = useAuth();

  const [agents, setAgents] = useState<AiAgent[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [drawerAgent, setDrawerAgent] = useState<AiAgent | null | undefined>(undefined);
  const [previewAgent, setPreviewAgent] = useState<AiAgent | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);

  const fetchAgents = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const res = await listAgents();
      setAgents(res.agents || []);
    } catch (err: unknown) {
      if (!isFeatureLockedError(err)) {
        toast.error(t('agent.failedToLoad', 'Failed to load agents') + (err instanceof Error ? ': ' + err.message : ''));
      }
    } finally {
      setLoading(false);
    }
  }, [restaurantId]);

  useEffect(() => { fetchAgents(); }, [fetchAgents]);

  const handleToggle = async (agent: AiAgent) => {
    try {
      await updateAgent(agent.id, { is_active: !agent.is_active });
      setAgents(prev => prev.map(a => a.id === agent.id ? { ...a, is_active: !a.is_active } : a));
    } catch (err: unknown) {
      toast.error(t('agent.failedToToggle', 'Failed to toggle') + (err instanceof Error ? ': ' + err.message : ''));
    }
  };

  const handleDelete = async (agent: AiAgent) => {
    if (deleteConfirm !== agent.id) {
      setDeleteConfirm(agent.id);
      toast(t('agent.confirmDelete', 'Click delete again to confirm'), { duration: 3000 });
      setTimeout(() => setDeleteConfirm(null), 3000);
      return;
    }
    try {
      await deleteAgent(agent.id);
      setAgents(prev => prev.filter(a => a.id !== agent.id));
      if (previewAgent?.id === agent.id) setPreviewAgent(null);
      toast.success(t('agent.deleted', 'Agent deleted'));
    } catch (err: unknown) {
      toast.error(t('agent.failedToDelete', 'Failed to delete') + (err instanceof Error ? ': ' + err.message : ''));
    } finally {
      setDeleteConfirm(null);
    }
  };

  const handleSaved = (saved: AiAgent, isNew: boolean) => {
    setAgents(prev => {
      let list = isNew ? [saved, ...prev] : prev.map(a => a.id === saved.id ? saved : a);
      if (saved.is_default) {
        list = list.map(a => a.id !== saved.id ? { ...a, is_default: false } : a);
      }
      return list;
    });
    setPreviewAgent(saved);
  };

  const filteredAgents = agents.filter(a =>
    a.name.toLowerCase().includes(search.toLowerCase()) ||
    a.role.toLowerCase().includes(search.toLowerCase())
  );

  const activePreview = previewAgent || (filteredAgents.length > 0 ? filteredAgents[0] : null);

  if (loading) return <InlineFormSkeleton sections={4} />;

  return (
    <FeatureGuard feature="chat_agent" featureName="AI Chat Agent">
    <>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="relative flex-1 max-w-sm">
          <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
          <input className="input-base pl-9" placeholder={t('agent.searchPlaceholder', 'Search agents...')} value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <button className="btn-primary" onClick={() => setDrawerAgent(null)}>
          <Plus size={16} /> {t('agent.newAgent', 'New Agent')}
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          {filteredAgents.length === 0 ? (
            <div className="text-center py-16 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Bot size={40} className="mx-auto mb-3 opacity-30" />
              <p className="font-medium">
                {agents.length === 0 ? t('agent.noAgentsYet', 'No agents yet') : t('agent.noAgentsMatch', 'No agents match your search')}
              </p>
              <p className="text-xs mt-1">
                {agents.length === 0
                  ? t('agent.createFirstAgent', 'Create your first AI agent to get started')
                  : t('common.tryDifferentSearch', 'Try a different search term')}
              </p>
              {agents.length === 0 && (
                <button className="btn-primary mt-4" onClick={() => setDrawerAgent(null)}>
                  <Plus size={16} /> {t('agent.createAgent', 'Create Agent')}
                </button>
              )}
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {filteredAgents.map(agent => (
                <AgentCard
                  key={agent.id}
                  agent={agent}
                  onEdit={a => { setDrawerAgent(a); setPreviewAgent(a); }}
                  onDelete={handleDelete}
                  onToggle={handleToggle}
                />
              ))}
            </div>
          )}
        </div>

        <div className="hidden lg:block">
          {activePreview ? (
            <AgentPreview
              name={activePreview.name}
              greeting={activePreview.greeting_script || ''}
              systemPrompt={activePreview.system_prompt || ''}
              closing={activePreview.closing_script || ''}
            />
          ) : (
            <div className="card p-5 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <Bot size={32} className="mx-auto mb-2 opacity-30" />
              <p className="text-xs">{t('agent.createToPreview', 'Create an agent to see a preview')}</p>
            </div>
          )}
        </div>
      </div>

      {drawerAgent !== undefined && (
        <AgentDrawer
          agent={drawerAgent}
          onClose={() => setDrawerAgent(undefined)}
          onSaved={handleSaved}
        />
      )}
    </>
    </FeatureGuard>
  );
}
