'use client';

import { useState, useEffect, useCallback } from 'react';
import { Phone, PhoneIncoming, PhoneOutgoing, ArrowRightLeft, Users, Clock, AlertCircle } from 'lucide-react';
import { toast } from 'sonner';
import { transferCallApi, createConferenceApi } from '@client/api/telephone';
import { useLanguage } from '@client/contexts/LanguageContext';

interface CallSession {
  id: string;
  sip_call_id: string | null;
  caller_number: string | null;
  callee_number: string | null;
  direction: string;
  status: string;
  started_at: string;
  ended_at: string | null;
  duration_seconds: number;
  escalated_to_human: boolean;
  agent_name?: string;
  phone_display_name?: string;
}

async function fetchCalls(params?: Record<string, string>): Promise<{ sessions: CallSession[]; total: number }> {
  const qs = new URLSearchParams(params || {});
  const res = await fetch(`/api/telephone/calls?${qs.toString()}`, { credentials: 'include' });
  const json = await res.json();
  if (!res.ok) throw new Error(json.error || 'Failed to load calls');
  return json;
}

export default function CallHistoryTab() {
  const { t } = useLanguage();
  const [calls, setCalls] = useState<CallSession[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<'all' | 'active' | 'completed'>('all');
  const [transferTarget, setTransferTarget] = useState<{ sessionId: string; number: string } | null>(null);
  const [conferenceTarget, setConferenceTarget] = useState<{ sessionId: string; staffNumber: string } | null>(null);
  const [conferenceResult, setConferenceResult] = useState<{ sessionId: string; name: string; staffCallSid?: string; staffNumberDialed?: string; staffJoinStatus?: string } | null>(null);

  const loadCalls = useCallback(async () => {
    setLoading(true);
    try {
      const params: Record<string, string> = { limit: '50' };
      if (filter !== 'all') params.status = filter;
      const res = await fetchCalls(params);
      setCalls(res.sessions || []);
      setTotal(res.total || 0);
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : 'Failed to load calls');
    } finally {
      setLoading(false);
    }
  }, [filter]);

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

  const handleTransfer = async (sessionId: string) => {
    if (!transferTarget || transferTarget.sessionId !== sessionId || !transferTarget.number.trim()) {
      toast.error(t('telephone.enterTransferNumber', 'Enter a transfer number'));
      return;
    }
    try {
      await transferCallApi(sessionId, transferTarget.number.trim());
      toast.success(t('telephone.callTransferred', 'Call transferred'));
      setTransferTarget(null);
      loadCalls();
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('telephone.transferFailed', 'Transfer failed'));
    }
  };

  const handleConference = async (sessionId: string) => {
    const staffNum = conferenceTarget?.sessionId === sessionId ? conferenceTarget.staffNumber.trim() : undefined;
    try {
      const res = await createConferenceApi(sessionId, staffNum || undefined);
      if (res.success) {
        const msg = res.staffJoinStatus === 'calling_staff'
          ? t('telephone.conferenceCallingStaff', 'Conference created. Calling staff at {{number}}.', { number: res.staffNumberDialed ?? '' })
          : res.staffJoinStatus === 'staff_call_failed'
          ? t('telephone.conferenceStaffFailed', 'Conference created but failed to call staff. Try entering a number manually.')
          : t('telephone.conferenceCreated', 'Conference created: {{name}}. Enter a staff number or set a fallback number on the phone line.', { name: res.conferenceName ?? '' });
        toast.success(msg);
        setConferenceTarget(null);
        setConferenceResult({ sessionId, name: res.conferenceName || '', staffCallSid: res.staffCallSid, staffNumberDialed: res.staffNumberDialed, staffJoinStatus: res.staffJoinStatus });
        loadCalls();
      }
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : t('telephone.conferenceFailed', 'Conference failed'));
    }
  };

  const formatDuration = (secs: number) => {
    if (!secs) return '--';
    const m = Math.floor(secs / 60);
    const s = secs % 60;
    return `${m}:${s.toString().padStart(2, '0')}`;
  };

  const formatTime = (ts: string) => {
    try { return new Date(ts).toLocaleString(); } catch { return ts; }
  };

  if (loading) {
    return (
      <div className="space-y-3">
        {[1, 2, 3].map(i => (
          <div key={i} className="card p-4 animate-pulse">
            <div className="h-4 rounded w-1/3 mb-2" style={{ backgroundColor: 'hsl(var(--muted))' }} />
            <div className="h-3 rounded w-1/2" style={{ backgroundColor: 'hsl(var(--muted))' }} />
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Phone size={16} style={{ color: 'hsl(var(--primary))' }} />
          <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('telephone.callHistory', 'Call History')}</h3>
          <span className="text-xs px-1.5 py-0.5 rounded-full" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}>{total}</span>
        </div>
        <div className="flex gap-1">
          {(['all', 'active', 'completed'] as const).map(f => (
            <button key={f} onClick={() => setFilter(f)}
              className="px-3 py-1.5 rounded-lg text-xs font-medium transition-all"
              style={{
                backgroundColor: filter === f ? 'hsl(var(--primary))' : 'hsl(var(--muted))',
                color: filter === f ? 'white' : 'hsl(var(--muted-foreground))',
              }}>
              {f === 'all' ? t('telephone.filterAll', 'All') : f === 'active' ? t('telephone.filterActive', 'Active') : t('telephone.filterCompleted', 'Completed')}
            </button>
          ))}
        </div>
      </div>

      {calls.length === 0 ? (
        <div className="text-center py-10 card p-5" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Phone size={28} className="mx-auto mb-2 opacity-30" />
          <p className="text-sm">{t('telephone.noCallsFound', 'No calls found')}</p>
        </div>
      ) : (
        <div className="space-y-2">
          {calls.map(call => {
            const isActive = call.status === 'active' || call.status === 'ringing';
            return (
              <div key={call.id} className="card p-4">
                <div className="flex items-center gap-3">
                  <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{
                    backgroundColor: isActive ? 'hsl(var(--success-bg))' : 'hsl(var(--muted))',
                  }}>
                    {call.direction === 'inbound'
                      ? <PhoneIncoming size={16} style={{ color: isActive ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }} />
                      : <PhoneOutgoing size={16} style={{ color: isActive ? 'hsl(var(--success))' : 'hsl(var(--muted-foreground))' }} />
                    }
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>
                        {call.direction === 'inbound' ? call.caller_number : call.callee_number}
                      </span>
                      <span className="text-xs px-1.5 py-0.5 rounded-full" style={{
                        backgroundColor: isActive ? 'hsl(var(--success-bg))' : call.status === 'completed' ? 'hsl(var(--muted))' : 'hsl(var(--destructive)/0.1)',
                        color: isActive ? 'hsl(var(--success))' : call.status === 'completed' ? 'hsl(var(--muted-foreground))' : 'hsl(var(--destructive))',
                      }}>
                        {call.status === 'active' ? t('telephone.statusActive', 'active') : call.status === 'ringing' ? t('telephone.statusRinging', 'ringing') : call.status === 'completed' ? t('telephone.statusCompleted', 'completed') : call.status}
                      </span>
                      {call.escalated_to_human && (
                        <AlertCircle size={12} style={{ color: 'hsl(var(--warning))' }} aria-label={t('telephone.escalatedToHuman', 'Escalated to human')} />
                      )}
                    </div>
                    <div className="flex items-center gap-3 mt-0.5 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      <span>{call.direction === 'inbound' ? t('telephone.directionInbound', 'inbound') : t('telephone.directionOutbound', 'outbound')}</span>
                      {call.agent_name && <span>{call.agent_name}</span>}
                      <span className="flex items-center gap-1"><Clock size={10} />{formatDuration(call.duration_seconds)}</span>
                      <span>{formatTime(call.started_at)}</span>
                    </div>
                  </div>

                  {isActive && (
                    <div className="flex items-center gap-2 shrink-0">
                      <button className="btn-secondary text-xs flex items-center gap-1"
                        onClick={() => setTransferTarget(transferTarget?.sessionId === call.id ? null : { sessionId: call.id, number: '' })}
                        title={t('telephone.transferCall', 'Transfer call')}>
                        <ArrowRightLeft size={12} /> {t('telephone.transfer', 'Transfer')}
                      </button>
                      <button className="btn-secondary text-xs flex items-center gap-1"
                        onClick={() => setConferenceTarget(conferenceTarget?.sessionId === call.id ? null : { sessionId: call.id, staffNumber: '' })}
                        title={t('telephone.createConference', 'Create conference')}>
                        <Users size={12} /> {t('telephone.conference', 'Conference')}
                      </button>
                    </div>
                  )}
                </div>

                {transferTarget?.sessionId === call.id && (
                  <div className="mt-3 flex items-center gap-2 pt-3 border-t" style={{ borderColor: 'hsl(var(--border))' }}>
                    <input className="input-base text-xs flex-1" placeholder="+1234567890"
                      value={transferTarget.number}
                      onChange={e => setTransferTarget({ ...transferTarget, number: e.target.value })}
                    />
                    <button className="btn-primary text-xs" onClick={() => handleTransfer(call.id)}>{t('telephone.transfer', 'Transfer')}</button>
                    <button className="btn-ghost text-xs" onClick={() => setTransferTarget(null)}>{t('telephone.cancel', 'Cancel')}</button>
                  </div>
                )}

                {conferenceTarget?.sessionId === call.id && (
                  <div className="mt-3 flex items-center gap-2 pt-3 border-t" style={{ borderColor: 'hsl(var(--border))' }}>
                    <input className="input-base text-xs flex-1" placeholder={t('telephone.staffNumberPlaceholder', 'Staff phone number (optional, uses fallback)')}
                      value={conferenceTarget.staffNumber}
                      onChange={e => setConferenceTarget({ ...conferenceTarget, staffNumber: e.target.value })}
                    />
                    <button className="btn-primary text-xs" onClick={() => handleConference(call.id)}>{t('telephone.startConference', 'Start Conference')}</button>
                    <button className="btn-ghost text-xs" onClick={() => setConferenceTarget(null)}>{t('telephone.cancel', 'Cancel')}</button>
                  </div>
                )}

                {conferenceResult?.sessionId === call.id && (
                  <div className="mt-3 pt-3 border-t space-y-1" style={{ borderColor: 'hsl(var(--border))' }}>
                    <div className="flex items-center gap-2 text-xs">
                      <Users size={12} style={{ color: 'hsl(var(--primary))' }} />
                      <span className="font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('telephone.conferenceWithName', 'Conference: {{name}}', { name: conferenceResult.name })}</span>
                    </div>
                    {conferenceResult.staffJoinStatus === 'calling_staff' && conferenceResult.staffNumberDialed && (
                      <p className="text-xs" style={{ color: 'hsl(var(--success))' }}>
                        {t('telephone.callingStaffAt', 'Calling staff at {{number}}...', { number: conferenceResult.staffNumberDialed })}
                      </p>
                    )}
                    {conferenceResult.staffJoinStatus === 'staff_call_failed' && (
                      <p className="text-xs" style={{ color: 'hsl(var(--destructive))' }}>
                        {t('telephone.failedToCallStaff', 'Failed to call staff. Use the Conference button to try again with a different number.')}
                      </p>
                    )}
                    {conferenceResult.staffJoinStatus === 'no_staff_number' && (
                      <p className="text-xs" style={{ color: 'hsl(var(--warning))' }}>
                        {t('telephone.conferenceIsLive', 'Conference is live. Use the Conference button above to dial a staff member in, or set a fallback number on the phone line.')}
                      </p>
                    )}
                    <button className="btn-ghost text-xs" onClick={() => setConferenceResult(null)}>{t('telephone.dismiss', 'Dismiss')}</button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
