// ═══════════════════════════════════════════════════════════════════
// KINGDOMID COMMAND — Clients List
// ═══════════════════════════════════════════════════════════════════

import { useEffect, useState }   from 'react';
import { Link }                  from 'react-router-dom';
import { apiGet, apiPatch }      from '../lib/firebase';
import {
  Users, Search, Plus, Phone, ExternalLink,
  ChevronRight, Filter,
} from 'lucide-react';

interface Client {
  id:                string;
  business_name:     string;
  niche:             string;
  owner_name:        string;
  owner_email:       string;
  status:            string;
  subscription_plan: string;
  twilio_phone_number: string | null;
  vapi_assistant_id_en: string | null;
  subdomain:         string;
  went_live_at:      string | null;
  staffCount:        number;
  dashboardUrl:      string;
}

const NICHE_LABELS: Record<string, string> = {
  christian_counseling: 'Christian Counseling',
  senior_care:          'Senior Care',
  medical_pediatric:    'Medical',
  chiropractic_pt:      'Chiro / PT',
  christian_school:     'Christian School',
  veterinary:           'Veterinary',
  funeral_home:         'Funeral Home',
  family_law:           'Family Law',
  home_services:        'Home Services',
  church_ministry:      'Church / Ministry',
  other:                'Other',
};

export default function ClientsPage() {
  const [clients, setClients] = useState<Client[]>([]);
  const [filtered, setFiltered] = useState<Client[]>([]);
  const [loading, setLoading]   = useState(true);
  const [search,  setSearch]    = useState('');
  const [filter,  setFilter]    = useState('all');

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

  useEffect(() => {
    let list = clients;
    if (search) {
      const q = search.toLowerCase();
      list = list.filter(c =>
        c.business_name.toLowerCase().includes(q) ||
        c.owner_email.toLowerCase().includes(q) ||
        c.owner_name.toLowerCase().includes(q)
      );
    }
    if (filter !== 'all') {
      list = list.filter(c => c.status === filter);
    }
    setFiltered(list);
  }, [clients, search, filter]);

  const loadClients = async () => {
    try {
      const res = await apiGet<{ clients: Client[] }>('/api/onboarding/clients');
      setClients(res.clients);
      setFiltered(res.clients);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const updateStatus = async (clientId: string, status: string) => {
    try {
      await apiPatch(`/api/onboarding/clients/${clientId}/status`, { status });
      loadClients();
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <div className="page-content">
      {/* Header */}
      <div className="flex-between mb-24">
        <div>
          <h1 style={{ fontSize: '1.6rem', marginBottom: 4 }}>Clients</h1>
          <p className="text-muted">{clients.length} total clients on the platform</p>
        </div>
        <Link to="/clients/new" className="btn btn-gold">
          <Plus size={16} /> Onboard New Client
        </Link>
      </div>

      {/* Filters */}
      <div className="card" style={{ marginBottom: 20 }}>
        <div style={{ padding: '16px 20px', display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ position: 'relative', flex: 1, minWidth: 200 }}>
            <Search size={16} style={{
              position:  'absolute',
              left:      12,
              top:       '50%',
              transform: 'translateY(-50%)',
              color:     'var(--gray-400)',
            }} />
            <input
              className="form-input"
              style={{ paddingLeft: 38 }}
              placeholder="Search businesses, owners, emails..."
              value={search}
              onChange={e => setSearch(e.target.value)}
            />
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {['all', 'active', 'trial', 'suspended'].map(s => (
              <button
                key={s}
                className={`btn btn-sm ${filter === s ? 'btn-primary' : 'btn-outline'}`}
                onClick={() => setFilter(s)}
                style={{ textTransform: 'capitalize' }}
              >
                {s}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="card">
        {loading ? (
          <div style={{ padding: 60, textAlign: 'center' }}>
            <div className="spinner" style={{ margin: '0 auto 16px' }} />
            <p className="text-muted">Loading clients...</p>
          </div>
        ) : filtered.length === 0 ? (
          <div className="empty-state">
            <Users />
            <h3>{search || filter !== 'all' ? 'No clients match your search' : 'No clients yet'}</h3>
            <p>{search || filter !== 'all' ? 'Try adjusting your search or filters' : 'Onboard your first client to get started'}</p>
            {!search && filter === 'all' && (
              <Link to="/clients/new" className="btn btn-gold" style={{ marginTop: 16 }}>
                <Plus size={16} /> Onboard First Client
              </Link>
            )}
          </div>
        ) : (
          <div className="table-wrap">
            <table>
              <thead>
                <tr>
                  <th>Business</th>
                  <th>Niche</th>
                  <th>Owner</th>
                  <th>Plan</th>
                  <th>Phone</th>
                  <th>Status</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(c => (
                  <tr key={c.id}>
                    <td>
                      <div style={{ fontWeight: 700, color: 'var(--navy)', marginBottom: 2 }}>
                        {c.business_name}
                      </div>
                      <div style={{ fontSize: 16, color: 'var(--gray-400)' }}>
                        {c.subdomain}.kingdomid.app
                      </div>
                    </td>
                    <td>
                      <span className="text-muted">{NICHE_LABELS[c.niche] || c.niche}</span>
                    </td>
                    <td>
                      <div style={{ fontSize: 16, fontWeight: 500 }}>{c.owner_name}</div>
                      <div style={{ fontSize: 16, color: 'var(--gray-400)' }}>{c.owner_email}</div>
                    </td>
                    <td>
                      <span className="badge badge-gold" style={{ textTransform: 'capitalize' }}>
                        {c.subscription_plan}
                      </span>
                    </td>
                    <td>
                      {c.twilio_phone_number ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <Phone size={13} color="var(--success)" />
                          <span style={{ fontSize: 15 }}>{c.twilio_phone_number}</span>
                        </div>
                      ) : (
                        <span className="text-muted">Not provisioned</span>
                      )}
                    </td>
                    <td>
                      <span className={`badge badge-${c.status}`} style={{ textTransform: 'capitalize' }}>
                        {c.status}
                      </span>
                    </td>
                    <td>
                      <div style={{ display: 'flex', gap: 6 }}>
                        <Link
                          to={`/clients/${c.id}`}
                          className="btn btn-outline btn-sm"
                        >
                          View <ChevronRight size={13} />
                        </Link>
                        <a
                          href={`https://${c.subdomain}.kingdomid.app`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="btn btn-ghost btn-sm"
                          title="Open client dashboard"
                        >
                          <ExternalLink size={13} />
                        </a>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
