'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Phone, Plus, Search, Edit2, Trash2, CheckCircle, XCircle, BarChart3, Server, PhoneCall, Mic, Loader2 } from 'lucide-react';
import ConfirmModal from '@client/components/ui/ConfirmModal';
import { listPhoneNumbers, deletePhoneNumber, PhoneNumber } from '@client/api/phone-numbers';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

export default function PhoneNumbersPage() {
  const { t } = useLanguage();
  usePageHeader(t('phoneNumbers.title', "Phone Numbers"), t('phoneNumbers.subtitle', "Manage purchased numbers and SIP trunks for your AI voice agent"));
  const [numbers, setNumbers] = useState<PhoneNumber[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
  const [deleting, setDeleting] = useState(false);

  useEffect(() => {
    setLoading(true);
    listPhoneNumbers()
      .then(res => { setNumbers(res.numbers); setError(null); })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  const filtered = numbers.filter(n =>
    !searchQuery || n.number.includes(searchQuery) || n.type.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const totalCalls = 0;
  const activeCount = numbers.filter(n => n.isActive).length;

  const numberToDelete = numbers.find(n => n.id === confirmDeleteId);

  const handleConfirmDelete = async () => {
    if (!confirmDeleteId) return;
    setDeleting(true);
    try {
      await deletePhoneNumber(confirmDeleteId);
      setNumbers(prev => prev.filter(n => n.id !== confirmDeleteId));
      setConfirmDeleteId(null);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to delete number');
    } finally {
      setDeleting(false);
    }
  };

  return (
    <>
      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
        {[
          { label: t('phoneNumbers.stats.totalNumbers', 'Total Numbers'), value: numbers.length, icon: <Phone size={16} />, color: 'hsl(var(--primary))' },
          { label: t('phoneNumbers.stats.active', 'Active'), value: activeCount, icon: <CheckCircle size={16} />, color: 'hsl(142, 72%, 29%)' },
          { label: t('phoneNumbers.stats.monthlyCalls', 'Monthly Calls'), value: totalCalls.toLocaleString(), icon: <PhoneCall size={16} />, color: 'hsl(210, 100%, 40%)' },
          { label: t('phoneNumbers.stats.sipTrunks', 'SIP Trunks'), value: numbers.filter(n => n.type === 'sip').length, icon: <Server size={16} />, color: 'hsl(38, 92%, 40%)' },
        ].map(stat => (
          <div key={stat.label} className="rounded-xl p-4" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <div className="flex items-center justify-between mb-2">
              <span style={{ color: stat.color }}>{stat.icon}</span>
            </div>
            <p className="text-xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{stat.value}</p>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{stat.label}</p>
          </div>
        ))}
      </div>

      {/* Actions */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-5">
        <div className="relative">
          <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
          <input type="text" placeholder={t('phoneNumbers.searchPlaceholder', "Search numbers...")} value={searchQuery} onChange={e => setSearchQuery(e.target.value)} className="input-field pl-9 w-64" />
        </div>
        <div className="flex gap-2">
          <Link href="/ai-agent-config/phone-numbers/sip" className="btn-secondary text-sm">
            <Server size={15} /> {t('phoneNumbers.addSipTrunk', 'Add SIP Trunk')}
          </Link>
          <Link href="/ai-agent-config/phone-numbers/buy" className="btn-primary text-sm">
            <Plus size={15} /> {t('phoneNumbers.buyPhoneNumber', 'Buy Phone Number')}
          </Link>
        </div>
      </div>

      {error && (
        <div className="mb-4 px-4 py-3 rounded-xl text-sm" style={{ backgroundColor: 'hsl(var(--danger-bg))', color: 'hsl(var(--danger))', border: '1px solid hsl(var(--danger-border))' }}>
          {error}
        </div>
      )}

      {/* Table */}
      <div className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
        {loading ? (
          <div className="flex items-center justify-center py-16 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
            <Loader2 size={20} className="animate-spin" /> {t('phoneNumbers.loading', 'Loading phone numbers…')}
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                  {[
                    t('phoneNumbers.table.number', 'Number'),
                    t('phoneNumbers.table.type', 'Type'),
                    t('phoneNumbers.table.status', 'Status'),
                    t('phoneNumbers.table.created', 'Created'),
                    t('phoneNumbers.table.actions', 'Actions')
                  ].map(h => (
                    <th key={h} className="text-left px-4 py-3 text-xs font-semibold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map((num, idx) => (
                  <tr key={num.id} style={{ borderBottom: idx < filtered.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                    <td className="px-4 py-3.5">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
                          <Phone size={14} />
                        </div>
                        <span className="text-sm font-mono font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{num.number}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3.5">
                      <span
                        className="text-xs font-semibold px-2 py-0.5 rounded-full"
                        style={{
                          backgroundColor: num.type === 'purchased' ? 'hsl(22, 100%, 96%)' : 'hsl(231, 40%, 96%)',
                          color: num.type === 'purchased' ? 'hsl(22, 89%, 48%)' : 'hsl(231, 40%, 45%)',
                        }}
                      >
                        {num.type === 'purchased' ? `📱 ${t('phoneNumbers.typePurchased', 'Purchased')}` : `🔌 ${t('phoneNumbers.typeSip', 'SIP Trunk')}`}
                      </span>
                    </td>
                    <td className="px-4 py-3.5">
                      <span
                        className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full w-fit"
                        style={{
                          backgroundColor: num.isActive ? 'hsl(142, 72%, 96%)' : 'hsl(220, 9%, 96%)',
                          color: num.isActive ? 'hsl(142, 72%, 29%)' : 'hsl(220, 9%, 46%)',
                        }}
                      >
                        {num.isActive ? <CheckCircle size={11} /> : <XCircle size={11} />}
                        {num.isActive ? t('phoneNumbers.statusActive', 'Active') : t('phoneNumbers.statusInactive', 'Inactive')}
                      </span>
                    </td>
                    <td className="px-4 py-3.5">
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {new Date(num.createdAt).toLocaleDateString()}
                      </span>
                    </td>
                    <td className="px-4 py-3.5">
                      <div className="flex items-center gap-1">
                        <Link
                          href={`/ai-agent-config/phone-numbers/${num.id}`}
                          className="p-1.5 rounded-lg transition-colors hover:bg-black/5"
                          title={t('common.edit', 'Edit')}
                        >
                          <Edit2 size={14} style={{ color: 'hsl(var(--muted-foreground))' }} />
                        </Link>
                        <button
                          className="p-1.5 rounded-lg transition-colors hover:bg-red-50"
                          title={t('common.remove', 'Remove')}
                          onClick={() => setConfirmDeleteId(num.id)}
                        >
                          <Trash2 size={14} style={{ color: 'hsl(var(--danger))' }} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {filtered.length === 0 && (
              <div className="text-center py-16" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <Phone size={32} className="mx-auto mb-3 opacity-30" />
                <p className="font-medium">{t('phoneNumbers.noNumbersFound', 'No phone numbers found')}</p>
                <p className="text-xs mt-1">{t('phoneNumbers.noNumbersHint', 'Buy a number or add a SIP trunk to get started')}</p>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Info box */}
      <div className="mt-4 p-4 rounded-xl flex items-start gap-3" style={{ backgroundColor: 'hsl(var(--info-bg))', border: '1px solid hsl(var(--info-border))' }}>
        <Mic size={16} style={{ color: 'hsl(var(--info))', flexShrink: 0, marginTop: 1 }} />
        <div>
          <p className="text-sm font-medium" style={{ color: 'hsl(var(--info))' }}>{t('phoneNumbers.infoTitle', 'How phone numbers work')}</p>
          <p className="text-xs mt-0.5 leading-relaxed" style={{ color: 'hsl(210, 100%, 35%)' }}>
            {t('phoneNumbers.infoText', 'Purchased numbers are hosted by RestroAgent. SIP trunks use your existing telephony provider. Both types can be assigned to your AI voice agent to handle inbound and outbound calls.')}
          </p>
        </div>
      </div>

      {/* Confirm delete modal */}
      <ConfirmModal
        isOpen={!!confirmDeleteId}
        onClose={() => { if (!deleting) setConfirmDeleteId(null); }}
        onConfirm={handleConfirmDelete}
        title={t('phoneNumbers.deleteTitle', "Remove phone number?")}
        description={t('phoneNumbers.deleteDescription', `Are you sure you want to remove ${numberToDelete?.number ?? 'this number'}? It will be unassigned from all agents and can no longer receive calls.`)}
        confirmLabel={t('phoneNumbers.deleteConfirm', "Remove Number")}
        variant="danger"
        isLoading={deleting}
      />
    </>
  );
}
