// ═══════════════════════════════════════════════════════════════════
// KINGDOMID CLIENT — KingdomVoice Calls Page
// ═══════════════════════════════════════════════════════════════════

import { useEffect, useState } from 'react';
import { useClient }           from '../hooks/useClient';
import { apiGet }              from '../lib/firebase';
import { Phone, AlertTriangle, Clock, Filter } from 'lucide-react';

interface Call {
  id:             string;
  caller_number:  string;
  call_outcome:   string;
  call_duration:  number | null;
  is_after_hours: boolean;
  is_crisis_flagged: boolean;
  summary:        string | null;
  transcript:     string | null;
  recording_url:  string | null;
  language:       string;
  created_at:     string;
}

const OUTCOMES: Record<string, { label: string; color: string }> = {
  appointment_booked: { label: 'Appointment Booked', color: 'var(--success)' },
  message_taken:      { label: 'Message Taken',      color: 'var(--info)' },
  faq_answered:       { label: 'FAQ Answered',        color: 'var(--gray-500)' },
  transferred:        { label: 'Transferred',         color: 'var(--warning)' },
  missed:             { label: 'Missed',              color: 'var(--error)' },
  no_answer:          { label: 'No Answer',           color: 'var(--error)' },
  crisis_flagged:     { label: 'Crisis Flagged',      color: 'var(--error)' },
  voicemail:          { label: 'Voicemail',           color: 'var(--gray-400)' },
  other:              { label: 'Other',               color: 'var(--gray-400)' },
};

function formatDuration(s: number | null) {
  if (!s) return '—';
  const m = Math.floor(s / 60);
  const sec = s % 60;
  return m > 0 ? `${m}m ${sec}s` : `${sec}s`;
}

function formatDate(str: string) {
  return new Date(str).toLocaleString('en-US', {
    month: 'short', day: 'numeric',
    hour: 'numeric', minute: '2-digit',
  });
}

export default function CallsPage() {
  const { client }            = useClient();
  const [calls, setCalls]     = useState<Call[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Call | null>(null);
  const [filter, setFilter]   = useState('all');

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

  const loadCalls = async () => {
    try {
      const res = await apiGet<{ calls: Call[] }>(`/api/client/${client!.id}/calls?limit=50`);
      setCalls(res.calls || []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const filtered = calls.filter(c => {
    if (filter === 'after_hours') return c.is_after_hours;
    if (filter === 'crisis')      return c.is_crisis_flagged;
    if (filter === 'booked')      return c.call_outcome === 'appointment_booked';
    return true;
  });

  return (
    <div className="page">
      <div className="flex-between mb-20">
        <div>
          <h1 style={{ fontSize: '1.4rem', marginBottom: 4 }}>KingdomVoice</h1>
          <p className="text-muted">{calls.length} total calls handled by your AI receptionist</p>
        </div>
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        {[
          { key: 'all',         label: 'All Calls' },
          { key: 'booked',      label: '📅 Appointments Booked' },
          { key: 'after_hours', label: '🌙 After Hours' },
          { key: 'crisis',      label: '⚠️ Crisis' },
        ].map(f => (
          <button
            key={f.key}
            className={`btn btn-sm ${filter === f.key ? 'btn-primary' : 'btn-outline'}`}
            onClick={() => setFilter(f.key)}
          >
            {f.label}
          </button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 380px' : '1fr', gap: 16 }}>
        {/* Calls table */}
        <div className="card">
          {loading ? (
            <div style={{ padding: 48, textAlign: 'center' }}>
              <div className="spinner" style={{ margin: '0 auto 12px' }} />
              <p className="text-muted">Loading calls...</p>
            </div>
          ) : filtered.length === 0 ? (
            <div className="empty-state">
              <Phone />
              <h3>No calls yet</h3>
              <p>Calls will appear here once your AI answers its first call</p>
            </div>
          ) : (
            <div className="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Caller</th>
                    <th>Outcome</th>
                    <th>Duration</th>
                    <th>Date</th>
                    <th>Flags</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map(call => {
                    const outcome = OUTCOMES[call.call_outcome] || OUTCOMES.other;
                    return (
                      <tr
                        key={call.id}
                        onClick={() => setSelected(selected?.id === call.id ? null : call)}
                        style={{ cursor: 'pointer', background: selected?.id === call.id ? 'var(--tan)' : undefined }}
                      >
                        <td>
                          <div style={{ fontWeight: 600 }}>{call.caller_number || 'Unknown'}</div>
                          {call.language === 'es' && <span style={{ fontSize: 10, color: 'var(--info)', fontWeight: 600 }}>ES</span>}
                        </td>
                        <td>
                          <span style={{ fontSize: 12, fontWeight: 600, color: outcome.color }}>
                            {outcome.label}
                          </span>
                        </td>
                        <td className="text-muted">{formatDuration(call.call_duration)}</td>
                        <td className="text-muted">{formatDate(call.created_at)}</td>
                        <td>
                          <div style={{ display: 'flex', gap: 4 }}>
                            {call.is_after_hours && <span title="After hours"><Clock size={13} color="var(--warning)" /></span>}
                            {call.is_crisis_flagged && <span title="Crisis flagged"><AlertTriangle size={13} color="var(--error)" /></span>}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Call detail panel */}
        {selected && (
          <div className="card" style={{ height: 'fit-content', position: 'sticky', top: 20 }}>
            <div className="card-header">
              <h2>Call Detail</h2>
              <button className="btn btn-ghost btn-sm" onClick={() => setSelected(null)}>✕</button>
            </div>
            <div className="card-body" style={{ padding: '16px 20px' }}>
              {selected.is_crisis_flagged && (
                <div className="alert alert-error" style={{ marginBottom: 16 }}>
                  <AlertTriangle size={16} />
                  This call was flagged as a crisis situation. Follow up required.
                </div>
              )}

              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[
                  { label: 'Caller',    value: selected.caller_number || 'Unknown' },
                  { label: 'Outcome',   value: OUTCOMES[selected.call_outcome]?.label || selected.call_outcome },
                  { label: 'Duration',  value: formatDuration(selected.call_duration) },
                  { label: 'Date',      value: formatDate(selected.created_at) },
                  { label: 'Language',  value: selected.language === 'es' ? 'Spanish' : 'English' },
                  { label: 'After Hours', value: selected.is_after_hours ? 'Yes' : 'No' },
                ].map(row => (
                  <div key={row.label} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '6px 0', borderBottom: '1px solid var(--gray-100)' }}>
                    <span style={{ color: 'var(--gray-500)', fontWeight: 500 }}>{row.label}</span>
                    <span style={{ fontWeight: 600, color: 'var(--navy)' }}>{row.value}</span>
                  </div>
                ))}
              </div>

              {selected.summary && (
                <div style={{ marginTop: 16 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--gray-400)', marginBottom: 8 }}>
                    AI Summary
                  </div>
                  <p style={{ fontSize: 13, lineHeight: 1.7, color: 'var(--gray-700)', background: 'var(--tan)', padding: '12px', borderRadius: 'var(--radius-sm)' }}>
                    {selected.summary}
                  </p>
                </div>
              )}

              {selected.transcript && (
                <div style={{ marginTop: 16 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--gray-400)', marginBottom: 8 }}>
                    Transcript
                  </div>
                  <div style={{
                    fontSize: 12, lineHeight: 1.8, color: 'var(--gray-700)',
                    background: 'var(--gray-100)', padding: '12px', borderRadius: 'var(--radius-sm)',
                    maxHeight: 200, overflowY: 'auto', whiteSpace: 'pre-wrap',
                  }}>
                    {selected.transcript}
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
