'use client';

import { useState } from 'react';
import { AlertTriangle, Phone, MessageSquare, ChevronRight, X, Clock } from 'lucide-react';
import { toast } from 'sonner';
import Link from 'next/link';
import type { Conversation } from '@client/api/conversations';
import { useLanguage } from '@client/contexts/LanguageContext';

interface EscalationAlertsProps {
  escalations: Conversation[];
  loading: boolean;
}

export default function EscalationAlerts({ escalations, loading }: EscalationAlertsProps) {
  const { t } = useLanguage();
  const [dismissed, setDismissed] = useState<string[]>([]);

  const handleDismiss = (id: string) => {
    setDismissed(prev => [...prev, id]);
    toast.success(t('dashboard.escalationMarkedHandled', 'Escalation marked as handled'));
  };

  const visible = escalations.filter(e => !dismissed.includes(e.id));

  if (loading) {
    return (
      <div className="card p-5">
        <div className="flex items-center gap-2 mb-3">
          <AlertTriangle size={16} style={{ color: 'hsl(var(--warning))' }} />
          <p className="section-label">{t('dashboard.escalationsRequiringAttention', 'Escalations Requiring Attention')}</p>
        </div>
        <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-4 w-32 bg-gray-200 rounded mb-2" />
              <div className="h-3 w-48 bg-gray-200 rounded" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (visible.length === 0) {
    return (
      <div className="card p-5">
        <div className="flex items-center gap-2 mb-3">
          <AlertTriangle size={16} style={{ color: 'hsl(var(--warning))' }} />
          <p className="section-label">{t('dashboard.escalationsRequiringAttention', 'Escalations Requiring Attention')}</p>
        </div>
        <div className="flex flex-col items-center justify-center py-6 text-center">
          <div className="w-10 h-10 rounded-full flex items-center justify-center mb-2" style={{ backgroundColor: 'hsl(var(--success-bg))', color: 'hsl(var(--success))' }}>
            <AlertTriangle size={18} />
          </div>
          <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('dashboard.noEscalations', 'No escalations right now')}</p>
          <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.aiHandlingAutonomously', 'Your AI agent is handling all conversations autonomously')}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="card p-5" style={{ borderColor: 'hsl(var(--danger-border))', backgroundColor: 'hsl(var(--danger-bg))' }}>
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <AlertTriangle size={16} style={{ color: 'hsl(var(--danger))' }} />
          <p className="text-sm font-semibold" style={{ color: 'hsl(var(--danger))' }}>{t('dashboard.escalationsRequiringAttention', 'Escalations Requiring Attention')}</p>
        </div>
        <span className="badge badge-danger">{t('dashboard.activeCount', `${visible.length} active`, { count: visible.length })}</span>
      </div>

      <div className="space-y-3">
        {visible.map(esc => {
          const lastMsg = esc.messages?.[esc.messages.length - 1];
          const topic = lastMsg?.text ?? t('dashboard.needsHumanAttention', 'Needs human attention');
          const timeAgo = new Date(esc.createdAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });

          return (
            <div key={esc.id} className="rounded-xl p-4 fade-in" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--danger-border))' }}>
              <div className="flex items-start justify-between gap-2 mb-2">
                <div className="flex items-center gap-2 min-w-0">
                  <div className="w-7 h-7 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--danger-bg))', color: 'hsl(var(--danger))' }}>
                    {esc.channel === 'voice' ? <Phone size={13} /> : <MessageSquare size={13} />}
                  </div>
                  <div className="min-w-0">
                    <p className="text-sm font-semibold truncate" style={{ color: 'hsl(var(--foreground))' }}>{esc.customerName}</p>
                  </div>
                </div>
                <div className="flex items-center gap-1 shrink-0">
                  <div className="flex items-center gap-1 text-xs" style={{ color: 'hsl(var(--warning))' }}>
                    <Clock size={11} />
                    <span className="font-mono">{timeAgo}</span>
                  </div>
                  <button onClick={() => handleDismiss(esc.id)} className="btn-ghost p-1" title={t('dashboard.dismissEscalation', 'Dismiss escalation')}>
                    <X size={13} />
                  </button>
                </div>
              </div>
              <p className="text-xs leading-relaxed mb-3 line-clamp-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>{topic}</p>
              <div className="flex items-center justify-between">
                <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t(`dashboard.channel.${esc.channel}`, esc.channel)}</span>
                <Link href={`/conversations/${esc.id}`} className="btn-primary text-xs px-3 py-1.5 flex items-center gap-1">
                  {t('dashboard.takeOver', 'Take Over')}
                  <ChevronRight size={12} />
                </Link>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
