'use client';

import { useState, useEffect } from 'react';
import { Mic, MessageSquare, CheckCircle2, AlertTriangle } from 'lucide-react';
import StatusBadge from '@client/components/ui/StatusBadge';
import { getAIConfig } from '@client/api/ai-config';
import type { DashboardStats } from '@client/api/analytics';
import { useLanguage } from '@client/contexts/LanguageContext';

interface AgentConfig {
  voiceEnabled: boolean;
  chatEnabled: boolean;
  model: string;
}

interface AgentStatusPanelProps {
  stats: DashboardStats | null;
  loading: boolean;
}

function normalizeConfig(raw: Record<string, unknown>): AgentConfig {
  return {
    voiceEnabled: Boolean(raw.voice_enabled ?? raw.voiceEnabled ?? true),
    chatEnabled: Boolean(raw.chat_enabled ?? raw.chatEnabled ?? true),
    model: String(raw.model ?? 'gpt-4o'),
  };
}

export default function AgentStatusPanel({ stats, loading }: AgentStatusPanelProps) {
  const { t } = useLanguage();
  const [config, setConfig] = useState<AgentConfig | null>(null);

  const [configError, setConfigError] = useState(false);

  useEffect(() => {
    getAIConfig()
      .then(res => setConfig(normalizeConfig(res.config)))
      .catch(() => setConfigError(true));
  }, []);

  const humanConvs = parseInt(stats?.conversations?.human_conversations ?? '0', 10);
  const avgConfidence = parseFloat(parseFloat(stats?.conversations?.period_avg_confidence ?? '0').toFixed(1));
  const aiVoiceConvs = parseInt(stats?.conversations?.period_ai_voice_conversations ?? '0', 10);
  const aiChatConvs = parseInt(stats?.conversations?.period_ai_chat_conversations ?? '0', 10);
  const recentVoiceEscalations = parseInt(stats?.conversations?.recent_voice_escalations ?? '0', 10);
  const recentChatEscalations = parseInt(stats?.conversations?.recent_chat_escalations ?? '0', 10);

  const voiceEnabled = config?.voiceEnabled ?? false;
  const chatEnabled = config?.chatEnabled ?? false;
  const modelName = config?.model ?? 'unknown';

  const agents = [
    {
      id: 'voice-agent',
      name: t('dashboard.voiceAgent', 'Voice Agent'),
      channel: 'voice' as const,
      enabled: voiceEnabled,
      activeSessions: aiVoiceConvs,
      avgConfidence,
      recentEscalations: recentVoiceEscalations,
    },
    {
      id: 'chat-agent',
      name: t('dashboard.chatAgent', 'Chat Agent'),
      channel: 'chat' as const,
      enabled: chatEnabled,
      activeSessions: aiChatConvs,
      avgConfidence,
      recentEscalations: recentChatEscalations,
    },
  ];

  const configLoaded = config !== null;
  const allHealthy = configLoaded && agents.every(a => a.enabled) && humanConvs === 0;

  if (loading) {
    return (
      <div className="card p-5" style={{ height: '100%' }}>
        <div className="h-4 w-32 bg-gray-200 rounded mb-4 animate-pulse" />
        <div className="space-y-3">
          {[1, 2].map(i => (
            <div key={i} className="rounded-xl p-4 animate-pulse" style={{ backgroundColor: 'hsl(var(--muted))' }}>
              <div className="h-9 w-full bg-gray-200 rounded mb-3" />
              <div className="h-4 w-24 bg-gray-200 rounded" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (configError && !configLoaded) {
    return (
      <div className="card p-5" style={{ height: '100%' }}>
        <p className="section-label mb-2">{t('dashboard.aiAgentStatus', 'AI Agent Status')}</p>
        <div className="rounded-xl p-4 text-center" style={{ backgroundColor: 'hsl(var(--warning-bg))', border: '1px solid hsl(var(--warning-border))' }}>
          <p className="text-sm font-semibold" style={{ color: 'hsl(var(--warning))' }}>{t('dashboard.unableToLoadConfig', 'Unable to load agent config')}</p>
          <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.checkAiConfig', 'Check AI configuration in settings')}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="card p-5" style={{ height: '100%' }}>
      <div className="flex items-center justify-between mb-4">
        <div>
          <p className="section-label">{t('dashboard.aiAgentStatus', 'AI Agent Status')}</p>
          <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.model', 'Model')}: {modelName}</p>
        </div>
        <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold" style={{ backgroundColor: allHealthy ? 'hsl(var(--success-bg))' : 'hsl(var(--warning-bg))', color: allHealthy ? 'hsl(var(--success))' : 'hsl(var(--warning))', border: `1px solid ${allHealthy ? 'hsl(var(--success-border))' : 'hsl(var(--warning-border))'}` }}>
          <span className="w-1.5 h-1.5 rounded-full bg-current animate-pulse" />
          {allHealthy ? t('dashboard.allSystemsOperational', 'All Systems Operational') : t('dashboard.escalatedCount', `${humanConvs} Escalated`, { count: humanConvs })}
        </div>
      </div>

      <div className="space-y-3">
        {agents.map(agent => (
          <div key={agent.id} className="rounded-xl p-4 transition-all duration-150" style={{ backgroundColor: 'hsl(var(--muted))', border: '1px solid hsl(var(--border))' }}>
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
                  {agent.channel === 'voice' ? <Mic size={16} /> : <MessageSquare size={16} />}
                </div>
                <div>
                  <p className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{agent.name}</p>
                  <p className="text-xs font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.aiAgent', 'AI Agent')}</p>
                </div>
              </div>
              <StatusBadge status={agent.enabled ? 'online' : 'offline'} dot size="sm" />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.active', 'Active')}</p>
                <p className="text-sm font-semibold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{agent.activeSessions} {agent.channel === 'voice' ? t('dashboard.calls', 'calls') : t('dashboard.chats', 'chats')}</p>
              </div>
              <div>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.confidence', 'Confidence')}</p>
                <p className="text-sm font-semibold font-mono tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{agent.avgConfidence}%</p>
              </div>
            </div>
            <div className="mt-3 flex items-center gap-1.5">
              {agent.enabled ? (
                agent.recentEscalations > 0 ? (
                  <>
                    <AlertTriangle size={12} style={{ color: 'hsl(var(--warning))' }} />
                    <p className="text-xs" style={{ color: 'hsl(var(--warning))' }}>
                      {t('dashboard.escalationCountLast24h', `${agent.recentEscalations} escalation${agent.recentEscalations !== 1 ? 's' : ''} in last 24h`, { count: agent.recentEscalations })}
                    </p>
                  </>
                ) : (
                  <>
                    <CheckCircle2 size={12} style={{ color: 'hsl(var(--success))' }} />
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.noRecentIncidents', 'No recent incidents')}</p>
                  </>
                )
              ) : (
                <p className="text-xs" style={{ color: 'hsl(var(--warning))' }}>{t('dashboard.agentDisabled', 'Agent disabled in config')}</p>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
