// ═══════════════════════════════════════════════════════════════════
// KINGDOMID COMMAND — KingdomSchedule Admin Page
// Cross-client appointment overview, stats, and management
// ═══════════════════════════════════════════════════════════════════

import { useEffect, useState } from 'react';
import { useNavigate }         from 'react-router-dom';
import { apiGet, apiPost }     from '../lib/firebase';
import {
  Calendar, Clock, Users, TrendingUp, CheckCircle,
  XCircle, AlertCircle, ChevronRight, RefreshCw,
  Search, Filter, MoreHorizontal, Phone, Zap,
} from 'lucide-react';

// ── Types ─────────────────────────────────────────────────────────
interface Appointment {
  id:             string;
  client_id:      string;
  business_name:  string;
  service_name:   string;
  service_color:  string;
  provider_name:  string;
  contact_name:   string;
  contact_phone:  string;
  start_time:     string;
  end_time:       string;
  status:         string;
  booked_by:      string;
  is_new_patient: boolean;
}

interface AdminStats {
  total:    number;
  today:    number;
  upcoming: number;
  by_status: Array<{ status: string; cnt: number }>;
}

interface ClientSummary {
  client_id:     string;
  business_name: string;
  total:         number;
  today:         number;
  upcoming:      number;
  no_shows:      number;
}

// ── Constants ─────────────────────────────────────────────────────
const STATUS_CONFIG: Record<string, { label: string; color: string; bg: string }> = {
  confirmed:  { label: 'Confirmed',  color: '#10B981', bg: '#ECFDF5' },
  cancelled:  { label: 'Cancelled',  color: '#EF4444', bg: '#FEF2F2' },
  completed:  { label: 'Completed',  color: '#6B7280', bg: '#F9FAFB' },
  no_show:    { label: 'No Show',    color: '#F59E0B', bg: '#FFFBEB' },
};

// ── Helpers ───────────────────────────────────────────────────────
function fmtDate(iso: string) {
  const d    = new Date(iso);
  const diff = (Date.now() - d.getTime()) / 1000;
  if (diff < 3600)   return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400)  return `${Math.floor(diff / 3600)}h ago`;
  if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
  return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

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

function fmtTime(iso: string) {
  return new Date(iso).toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
}

function isoDate(d: Date) {
  return d.toISOString().split('T')[0];
}

function StatusPill({ status }: { status: string }) {
  const cfg = STATUS_CONFIG[status] || { label: status, color: '#6B7280', bg: '#F9FAFB' };
  return (
    <span style={{ fontSize: 16, fontWeight: 800, padding: '2px 7px', borderRadius: 12, background: cfg.bg, color: cfg.color, textTransform: 'uppercase', letterSpacing: 0.5, whiteSpace: 'nowrap' }}>
      {cfg.label}
    </span>
  );
}

// ═══════════════════════════════════════════════════════════════════
//  MAIN PAGE
// ═══════════════════════════════════════════════════════════════════
export default function KingdomSchedulePage() {
  const navigate                          = useNavigate();
  const [appointments, setAppointments]   = useState<Appointment[]>([]);
  const [stats, setStats]                 = useState<AdminStats | null>(null);
  const [clientSummaries, setClientSums]  = useState<ClientSummary[]>([]);
  const [loading, setLoading]             = useState(true);
  const [search, setSearch]               = useState('');
  const [statusFilter, setStatusFilter]   = useState('');
  const [clientFilter, setClientFilter]   = useState('');
  const [activeTab, setActiveTab]         = useState<'appointments' | 'clients'>('appointments');

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

  const loadAll = async () => {
    setLoading(true);
    await Promise.all([loadAppointments(), loadStats(), loadClientSummaries()]);
    setLoading(false);
  };

  const loadAppointments = async () => {
    try {
      const start = new Date(); start.setDate(start.getDate() - 7);
      const end   = new Date(); end.setDate(end.getDate() + 30);
      const r = await apiGet<{ appointments: Appointment[] }>(
        `/api/schedule/admin/appointments?start=${isoDate(start)}&end=${isoDate(end)}`
      );
      setAppointments(r.appointments || []);
    } catch {}
  };

  const loadStats = async () => {
    try {
      setStats(await apiGet<AdminStats>('/api/schedule/admin/stats'));
    } catch {}
  };

  const loadClientSummaries = async () => {
    try {
      // Aggregate per-client stats from the appointments
      const r = await apiGet<{ appointments: Appointment[] }>(
        `/api/schedule/admin/appointments?start=${isoDate(new Date())}&end=${isoDate(new Date(Date.now() + 30 * 86400000))}`
      );
      const appts = r.appointments || [];
      const map: Record<string, ClientSummary> = {};
      const todayStr = isoDate(new Date());

      appts.forEach((a: Appointment) => {
        if (!map[a.client_id]) {
          map[a.client_id] = { client_id: a.client_id, business_name: a.business_name, total: 0, today: 0, upcoming: 0, no_shows: 0 };
        }
        map[a.client_id].total++;
        if (isoDate(new Date(a.start_time)) === todayStr) map[a.client_id].today++;
        if (new Date(a.start_time) > new Date() && a.status === 'confirmed') map[a.client_id].upcoming++;
        if (a.status === 'no_show') map[a.client_id].no_shows++;
      });

      setClientSums(Object.values(map).sort((a, b) => b.total - a.total));
    } catch {}
  };

  // Filtered appointments
  const filtered = appointments.filter(a => {
    if (statusFilter && a.status !== statusFilter) return false;
    if (clientFilter && a.client_id !== clientFilter) return false;
    if (search) {
      const q = search.toLowerCase();
      return (
        a.contact_name?.toLowerCase().includes(q) ||
        a.contact_phone?.includes(q) ||
        a.service_name?.toLowerCase().includes(q) ||
        a.business_name?.toLowerCase().includes(q)
      );
    }
    return true;
  });

  // Unique clients for filter
  const clients = Array.from(new Map(appointments.map(a => [a.client_id, a.business_name])).entries());

  // Today's appointments
  const todayStr   = isoDate(new Date());
  const todayAppts = appointments.filter(a => isoDate(new Date(a.start_time)) === todayStr);

  if (loading) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '60vh' }}>
      <div style={{ textAlign: 'center', color: '#9CA3AF' }}>
        <div className="spinner" style={{ margin: '0 auto 12px' }} />
        <p style={{ margin: 0, fontSize: 15 }}>Loading KingdomSchedule…</p>
      </div>
    </div>
  );

  const byStatus = stats?.by_status || [];
  const confirmed  = byStatus.find(s => s.status === 'confirmed')?.cnt  || 0;
  const completed  = byStatus.find(s => s.status === 'completed')?.cnt  || 0;
  const noShows    = byStatus.find(s => s.status === 'no_show')?.cnt    || 0;
  const cancelled  = byStatus.find(s => s.status === 'cancelled')?.cnt  || 0;

  return (
    <div style={{ minHeight: '100vh', background: '#F5F6FA' }}>

      {/* ── Top chrome ── */}
      <div style={{ background: '#fff', borderBottom: '1px solid #E5E8EF', padding: '16px 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: '2rem', fontWeight: 900, color: '#0D1B3E', letterSpacing: -0.4 }}>KingdomSchedule</h1>
            <p style={{ margin: '2px 0 0', fontSize: 16, color: '#9CA3AF' }}>
              All appointments across all clients
            </p>
          </div>
          <button onClick={loadAll} style={{ display: 'flex', alignItems: 'center', gap: 6, background: '#F3F4F6', border: '1px solid #E5E7EB', borderRadius: 7, padding: '8px 14px', cursor: 'pointer', fontSize: 16, fontWeight: 600, color: '#374151' }}>
            <RefreshCw size={13} /> Refresh
          </button>
        </div>

        {/* ── Stat strip ── */}
        {stats && (
          <div style={{ display: 'flex', marginTop: 14, borderTop: '1px solid #F0F2F7', paddingTop: 14, gap: 0 }}>
            {[
              { label: 'Total',     value: stats.total,    color: '#3B82F6' },
              { label: 'Today',     value: stats.today,    color: '#C9A227' },
              { label: 'Upcoming',  value: stats.upcoming, color: '#10B981' },
              { label: 'Confirmed', value: confirmed,       color: '#10B981' },
              { label: 'Completed', value: completed,       color: '#6B7280' },
              { label: 'No-Shows',  value: noShows,         color: '#F59E0B' },
              { label: 'Cancelled', value: cancelled,       color: '#EF4444' },
            ].map((s, i, arr) => (
              <div key={s.label} style={{ flex: 1, paddingRight: i < arr.length - 1 ? 16 : 0, borderRight: i < arr.length - 1 ? '1px solid #F0F2F7' : 'none', paddingLeft: i > 0 ? 16 : 0 }}>
                <div style={{ fontSize: '1.15rem', fontWeight: 900, color: s.color, lineHeight: 1 }}>{s.value}</div>
                <div style={{ fontSize: 16, color: '#9CA3AF', fontWeight: 600, marginTop: 3, textTransform: 'uppercase', letterSpacing: 0.5 }}>{s.label}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ── Today strip ── */}
      {todayAppts.length > 0 && (
        <div style={{ background: '#fff', borderBottom: '1px solid #E5E8EF', padding: '12px 24px' }}>
          <div style={{ fontSize: 16, fontWeight: 800, color: '#9CA3AF', textTransform: 'uppercase', letterSpacing: 0.7, marginBottom: 10 }}>Today — {todayAppts.length} appointments</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {todayAppts.map(a => (
              <div key={a.id} style={{ display: 'flex', alignItems: 'center', gap: 8, background: `${a.service_color || '#0D1B3E'}10`, border: `1px solid ${a.service_color || '#0D1B3E'}25`, borderRadius: 8, padding: '7px 11px' }}>
                <div style={{ width: 7, height: 7, borderRadius: '50%', background: a.service_color || '#0D1B3E', flexShrink: 0 }} />
                <div>
                  <div style={{ fontSize: 16, fontWeight: 700, color: '#0D1B3E' }}>{fmtTime(a.start_time)} — {a.contact_name || 'Unknown'}</div>
                  <div style={{ fontSize: 16, color: '#9CA3AF' }}>{a.business_name} · {a.service_name}</div>
                </div>
                <StatusPill status={a.status} />
                {a.booked_by === 'vapi' && <span style={{ fontSize: 16, color: '#8B5CF6', fontWeight: 700 }}>🤖</span>}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Tab bar ── */}
      <div style={{ background: '#fff', borderBottom: '1px solid #E5E8EF', padding: '0 24px', display: 'flex', gap: 0 }}>
        {[
          { k: 'appointments', label: 'All Appointments' },
          { k: 'clients',      label: 'By Client' },
        ].map(t => (
          <button key={t.k} onClick={() => setActiveTab(t.k as any)}
            style={{ padding: '11px 16px', border: 'none', background: 'none', cursor: 'pointer', fontSize: 16, fontWeight: activeTab === t.k ? 800 : 500, color: activeTab === t.k ? '#0D1B3E' : '#9CA3AF', borderBottom: `2px solid ${activeTab === t.k ? '#C9A227' : 'transparent'}`, marginBottom: -1 }}>
            {t.label}
          </button>
        ))}
      </div>

      <div style={{ padding: '16px 24px' }}>

        {/* APPOINTMENTS TAB */}
        {activeTab === 'appointments' && (
          <>
            {/* Toolbar */}
            <div style={{ display: 'flex', gap: 8, marginBottom: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              <div style={{ position: 'relative', flex: '1 1 220px', maxWidth: 320 }}>
                <Search size={13} style={{ position: 'absolute', left: 9, top: '50%', transform: 'translateY(-50%)', color: '#9CA3AF', pointerEvents: 'none' }} />
                <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search contact, service, business…"
                  style={{ width: '100%', padding: '8px 10px 8px 29px', borderRadius: 7, border: '1.5px solid #E5E7EB', fontSize: 16, boxSizing: 'border-box', background: '#fff' }} />
              </div>
              <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)}
                style={{ padding: '8px 10px', borderRadius: 7, border: '1.5px solid #E5E7EB', fontSize: 16, color: '#374151', background: '#fff' }}>
                <option value="">All Statuses</option>
                {Object.entries(STATUS_CONFIG).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
              </select>
              <select value={clientFilter} onChange={e => setClientFilter(e.target.value)}
                style={{ padding: '8px 10px', borderRadius: 7, border: '1.5px solid #E5E7EB', fontSize: 16, color: '#374151', background: '#fff' }}>
                <option value="">All Clients</option>
                {clients.map(([id, name]) => <option key={id} value={id}>{name}</option>)}
              </select>
              <span style={{ marginLeft: 'auto', fontSize: 15, color: '#9CA3AF', fontWeight: 600 }}>{filtered.length} appointments</span>
            </div>

            {/* Table */}
            <div style={{ background: '#fff', border: '1px solid #E5E8EF', borderRadius: 10, overflow: 'hidden' }}>
              {filtered.length === 0 ? (
                <div style={{ padding: '56px 24px', textAlign: 'center', color: '#9CA3AF' }}>
                  <Calendar size={28} style={{ margin: '0 auto 12px', display: 'block', opacity: 0.3 }} />
                  <p style={{ margin: 0, fontWeight: 700, color: '#374151', fontSize: 16 }}>No appointments found</p>
                  <p style={{ margin: '4px 0 0', fontSize: 15 }}>Appointments appear here once clients have KingdomSchedule set up.</p>
                </div>
              ) : (
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr style={{ background: '#F8F9FB', borderBottom: '1.5px solid #E9EBF0' }}>
                      {['Date & Time', 'Client', 'Service', 'Contact', 'Provider', 'Status', 'Booked By'].map(h => (
                        <th key={h} style={{ padding: '9px 14px', textAlign: 'left', fontSize: 16, fontWeight: 800, color: '#9CA3AF', textTransform: 'uppercase', letterSpacing: 0.7, whiteSpace: 'nowrap' }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {filtered
                      .sort((a, b) => new Date(b.start_time).getTime() - new Date(a.start_time).getTime())
                      .map((a, i, arr) => (
                        <tr key={a.id}
                          style={{ borderBottom: i < arr.length - 1 ? '1px solid #F3F5F8' : 'none' }}
                          onMouseEnter={e => (e.currentTarget.style.background = '#FAFBFD')}
                          onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}>
                          <td style={{ padding: '10px 14px', whiteSpace: 'nowrap' }}>
                            <div style={{ fontSize: 15, fontWeight: 700, color: '#0D1B3E' }}>
                              {new Date(a.start_time).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}
                            </div>
                            <div style={{ fontSize: 15, color: '#9CA3AF', marginTop: 2 }}>{fmtTime(a.start_time)} — {fmtTime(a.end_time)}</div>
                          </td>
                          <td style={{ padding: '10px 14px' }}>
                            <div style={{ fontSize: 15, fontWeight: 700, color: '#0D1B3E' }}>{a.business_name}</div>
                          </td>
                          <td style={{ padding: '10px 14px' }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                              <span style={{ width: 9, height: 9, borderRadius: '50%', background: a.service_color || '#0D1B3E', flexShrink: 0 }} />
                              <span style={{ fontSize: 16, fontWeight: 600, color: '#374151' }}>{a.service_name || '—'}</span>
                            </div>
                          </td>
                          <td style={{ padding: '10px 14px' }}>
                            <div style={{ fontSize: 15, fontWeight: 700, color: '#0D1B3E' }}>{a.contact_name || <span style={{ color: '#9CA3AF', fontStyle: 'italic', fontWeight: 400 }}>Unknown</span>}</div>
                            <div style={{ fontSize: 15, color: '#9CA3AF', marginTop: 1 }}>{a.contact_phone || '—'}</div>
                          </td>
                          <td style={{ padding: '10px 14px', fontSize: 16, color: '#6B7280' }}>{a.provider_name || '—'}</td>
                          <td style={{ padding: '10px 14px' }}><StatusPill status={a.status} /></td>
                          <td style={{ padding: '10px 14px' }}>
                            <span style={{ fontSize: 15, fontWeight: 700, color: a.booked_by === 'vapi' ? '#8B5CF6' : '#6B7280' }}>
                              {a.booked_by === 'vapi' ? '🤖 AI' : a.booked_by || 'staff'}
                            </span>
                            {a.is_new_patient && (
                              <span style={{ marginLeft: 6, fontSize: 9, fontWeight: 800, padding: '1px 5px', borderRadius: 8, background: '#FEF3C7', color: '#92400E', textTransform: 'uppercase' }}>NEW</span>
                            )}
                          </td>
                        </tr>
                      ))}
                  </tbody>
                </table>
              )}
            </div>
          </>
        )}

        {/* BY CLIENT TAB */}
        {activeTab === 'clients' && (
          <div>
            {clientSummaries.length === 0 ? (
              <div style={{ background: '#fff', border: '1px solid #E5E8EF', borderRadius: 10, padding: '56px 24px', textAlign: 'center', color: '#9CA3AF' }}>
                <Users size={28} style={{ margin: '0 auto 12px', display: 'block', opacity: 0.3 }} />
                <p style={{ margin: 0, fontWeight: 700, color: '#374151', fontSize: 16 }}>No client schedule data yet</p>
              </div>
            ) : (
              <div style={{ background: '#fff', border: '1px solid #E5E8EF', borderRadius: 10, overflow: 'hidden' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr style={{ background: '#F8F9FB', borderBottom: '1.5px solid #E9EBF0' }}>
                      {['Client', 'Total Appts', 'Today', 'Upcoming', 'No-Shows', ''].map(h => (
                        <th key={h} style={{ padding: '9px 14px', textAlign: 'left', fontSize: 16, fontWeight: 800, color: '#9CA3AF', textTransform: 'uppercase', letterSpacing: 0.7 }}>{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {clientSummaries.map((c, i) => (
                      <tr key={c.client_id}
                        style={{ borderBottom: i < clientSummaries.length - 1 ? '1px solid #F3F5F8' : 'none', cursor: 'pointer' }}
                        onMouseEnter={e => (e.currentTarget.style.background = '#FAFBFD')}
                        onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
                        onClick={() => { setClientFilter(c.client_id); setActiveTab('appointments'); }}>
                        <td style={{ padding: '12px 14px' }}>
                          <div style={{ fontWeight: 800, fontSize: 15, color: '#0D1B3E' }}>{c.business_name}</div>
                        </td>
                        <td style={{ padding: '12px 14px', fontSize: 16, fontWeight: 800, color: '#374151' }}>{c.total}</td>
                        <td style={{ padding: '12px 14px' }}>
                          <span style={{ fontSize: 15, fontWeight: 800, color: c.today > 0 ? '#C9A227' : '#9CA3AF' }}>{c.today}</span>
                        </td>
                        <td style={{ padding: '12px 14px' }}>
                          <span style={{ fontSize: 15, fontWeight: 800, color: c.upcoming > 0 ? '#10B981' : '#9CA3AF' }}>{c.upcoming}</span>
                        </td>
                        <td style={{ padding: '12px 14px' }}>
                          <span style={{ fontSize: 15, fontWeight: 800, color: c.no_shows > 0 ? '#F59E0B' : '#9CA3AF' }}>{c.no_shows}</span>
                        </td>
                        <td style={{ padding: '12px 14px' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 4, color: '#9CA3AF', fontSize: 16 }}>
                            View <ChevronRight size={13} />
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
