import { useState } from 'react';
import api from '../utils/api';
import { fmt, fmtD, toLocal, REFERRAL_BONUS } from '../utils/helpers';
import { Icons } from '../components/icons/Icons';
import { Badge, VipBadge, ClientName } from '../components/ui/Badge';
import Modal from '../components/ui/Modal';
import Confirm from '../components/ui/Confirm';
import Field from '../components/ui/Field';
import PhoneInput, { validatePhone } from '../components/ui/PhoneInput';
import OrderDetailModal from '../components/ui/OrderDetailModal';

const isValidEmail = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);

export default function Clients({ products, clients, orders, refetch, nav }) {
  const [search, setSearch] = useState('');
  const [modal, setModal] = useState(null);
  const [form, setForm] = useState({});
  const [formErrors, setFormErrors] = useState({});
  const [showDel, setShowDel] = useState(false);
  const [detail, setDetail] = useState(null);
  const [cfm, setCfm] = useState(null);
  const [restoreCfm, setRestoreCfm] = useState(null);
  const [viewOrder, setViewOrder] = useState(null);
  const [sortBy, setSortBy] = useState('name');
  const [filterVip, setFilterVip] = useState('all');
  const [orderSearch, setOrderSearch] = useState('');
  const [orderSort, setOrderSort] = useState('newest');

  const clientSpent = (cid) => orders.filter((o) => o.client_id === cid && o.status === 'confirmed').reduce((s, o) => s + parseFloat(o.total), 0);
  const referralEarnings = (cid) => orders.filter((o) => o.referral_from === cid && o.status === 'confirmed').length * REFERRAL_BONUS;

  let list = clients
    .filter((c) => (showDel ? c.is_deleted : !c.is_deleted))
    .filter((c) => c.name.toLowerCase().includes(search.toLowerCase()) || (c.phone || '').includes(search));
  if (filterVip === 'vip') list = list.filter((c) => c.is_vip);
  if (filterVip === 'regular') list = list.filter((c) => !c.is_vip);
  if (sortBy === 'name') list = [...list].sort((a, b) => a.name.localeCompare(b.name));
  else if (sortBy === 'spent') list = [...list].sort((a, b) => clientSpent(b.id) - clientSpent(a.id));

  const validateForm = () => {
    const e = {};
    if (!form.name?.trim()) e.name = 'Name is required';
    if (!form.phone?.trim()) e.phone = 'Phone is required';
    else { const phoneErr = validatePhone(form.phone); if (phoneErr) e.phone = phoneErr; }
    if (!form.email?.trim()) e.email = 'Email is required';
    else if (!isValidEmail(form.email)) e.email = 'Invalid email format';
    if (!form.address?.trim()) e.address = 'Address is required';
    if (!form.birth_date) e.birth_date = 'Date of birth is required';
    if (!form.allergies?.trim()) e.allergies = 'Allergies is required (or type "None")';
    setFormErrors(e);
    return Object.keys(e).length === 0;
  };

  const save = async () => {
    if (!validateForm()) return;
    try {
      const payload = { name: form.name, phone: form.phone || '', email: form.email || '', address: form.address || '', allergies: form.allergies || '', notes: form.notes || '', birth_date: form.birth_date || null };
      if (modal === 'add') await api.post('/clients', payload);
      else await api.put(`/clients/${form.id}`, payload);
      setModal(null); setFormErrors({}); refetch();
    } catch (err) {
      const msg = err.response?.data?.error || 'Error';
      if (msg.includes('Phone')) setFormErrors({ phone: msg });
      else if (msg.includes('Email')) setFormErrors({ email: msg });
      else alert(msg);
    }
  };

  const handleDelete = async () => { try { await api.delete(`/clients/${cfm.id}`); setCfm(null); refetch(); } catch {} };
  const handleRestore = async () => { try { await api.put(`/clients/${restoreCfm.id}/restore`); setRestoreCfm(null); refetch(); } catch {} };
  const handleToggleVip = async (id) => {
    try { await api.put(`/clients/${id}/toggle-vip`); refetch(); if (detail?.id === id) setDetail({ ...detail, is_vip: !detail.is_vip }); } catch {}
  };

  const cO = detail ? orders.filter((o) => o.client_id === detail.id).sort((a, b) => (b.order_date || '').localeCompare(a.order_date || '')) : [];
  const referredClients = detail ? clients.filter((c) => c.referred_by === detail.id && !c.is_deleted) : [];

  return (
    <div>
      <div className="flex justify-between items-center mb-1">
        <div>
          <h1 className="text-xl font-bold mb-0.5">Clients</h1>
          <p className="text-t2 text-xs mb-5">{clients.filter((c) => !c.is_deleted).length} active · {clients.filter((c) => !c.is_deleted && c.is_vip).length} VIP</p>
        </div>
        <div className="flex gap-1.5">
          <button className={`px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 border ${showDel ? 'bg-ac text-white border-ac' : 'border-bd text-t2 hover:bg-s2'}`} onClick={() => setShowDel(!showDel)}>
            <Icons.Trash /> {showDel ? 'Active' : 'Deleted'}
          </button>
          <button className="bg-ac text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-ac/90" onClick={() => { setForm({ name: '', phone: '', email: '', address: '', allergies: '', notes: '', birth_date: '' }); setFormErrors({}); setModal('add'); }}>
            <Icons.Plus /> Add
          </button>
        </div>
      </div>

      <div className="flex gap-2 mb-3.5 flex-wrap items-center">
        <div className="flex items-center gap-2 bg-s2 border border-bd rounded-md px-2.5 py-1 flex-1 max-w-[240px]">
          <Icons.Search />
          <input className="bg-transparent border-none text-t1 text-[13px] w-full outline-none" placeholder="Search..." value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
        {[{ k: 'all', l: 'All' }, { k: 'vip', l: '⭐ VIP' }, { k: 'regular', l: 'Regular' }].map((f) => (
          <button key={f.k} className={`px-2.5 py-1 rounded-md text-[11px] font-semibold border ${filterVip === f.k ? (f.k === 'vip' ? 'bg-gradient-to-br from-gold to-or text-white border-gold' : 'bg-ac text-white border-ac') : 'border-bd text-t2 hover:bg-s2'}`} onClick={() => setFilterVip(f.k)}>{f.l}</button>
        ))}
        <select className="bg-s2 border border-bd rounded-md text-t1 text-[11px] px-2.5 py-1.5 outline-none" value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
          <option value="name">A-Z</option>
          <option value="spent">Top Spender</option>
        </select>
      </div>

      <div className="grid grid-cols-[repeat(auto-fill,minmax(290px,1fr))] gap-2.5">
        {list.map((c) => {
          const spent = clientSpent(c.id);
          const refE = referralEarnings(c.id);
          const orderCount = orders.filter((o) => o.client_id === c.id && o.status === 'confirmed').length;
          const referrer = c.referred_by ? clients.find((x) => x.id === c.referred_by) : null;
          return (
            <div key={c.id} className={`bg-s1 border rounded-[10px] p-4 cursor-pointer transition-colors hover:border-ac ${c.is_vip ? 'border-gold/30' : 'border-bd'} ${c.is_deleted ? 'opacity-50' : ''}`}
              onClick={() => { if (!c.is_deleted) { setDetail(c); setOrderSearch(''); setOrderSort('newest'); } }}>
              <div className="flex justify-between items-start">
                <div>
                  <div className={`font-bold text-sm flex items-center gap-1.5 ${c.is_vip ? 'text-gold' : 'text-t1'}`}>
                    {c.is_vip ? <Icons.Crown /> : null}{c.name}{c.is_vip ? <span className="ml-1"><VipBadge /></span> : null}
                  </div>
                  <div className="text-t2 text-[11px]">{c.phone}</div>
                </div>
                <div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
                  {!c.is_deleted ? (
                    <>
                      <button className={`px-2 py-0.5 rounded text-[10px] font-semibold border ${c.is_vip ? 'bg-gradient-to-br from-gold to-or text-white border-gold' : 'border-bd text-t2'}`} onClick={() => handleToggleVip(c.id)}><Icons.Crown /></button>
                      <button className="px-1 py-0.5 text-t2 hover:text-ac" onClick={() => { setForm({ ...c }); setFormErrors({}); setModal(c); }}><Icons.Edit /></button>
                      <button className="px-1 py-0.5 text-rd" onClick={() => setCfm(c)}><Icons.Trash /></button>
                    </>
                  ) : null}
                  {c.is_deleted ? <button className="px-1 py-0.5 text-gr" onClick={() => setRestoreCfm(c)}><Icons.Undo /></button> : null}
                </div>
              </div>
              {referrer && <div className="text-[10px] text-pr mt-0.5 flex gap-1 items-center"><Icons.Link /> Referred by {referrer.name}</div>}
              <div className="flex gap-3 mt-2.5 pt-2 border-t border-bd">
                {spent > 0 && <div><div className="text-[10px] text-t2">Spent</div><div className="text-sm font-bold text-gr">{fmt(spent)}</div></div>}
                {orderCount > 0 && <div><div className="text-[10px] text-t2">Orders</div><div className="text-sm font-bold">{orderCount}</div></div>}
                {refE > 0 && <div><div className="text-[10px] text-t2">Ref.</div><div className="text-sm font-bold text-pr">{fmt(refE)}</div></div>}
                {spent === 0 && orderCount === 0 && <div className="text-[10px] text-t3">No orders yet</div>}
              </div>
            </div>
          );
        })}
      </div>

      {/* Delete confirm */}
      <Confirm open={!!cfm} onClose={() => setCfm(null)} icon="🗑️" title="Delete Client?" desc={`Delete "${cfm?.name}"?`} cStyle="d" cLabel="Yes, Delete"
        details={[{ i: '📋', t: 'Soft delete' }, { i: '🔄', t: 'Restorable from Settings' }]}
        onConfirm={handleDelete}
      />

      {/* Restore confirm */}
      <Confirm open={!!restoreCfm} onClose={() => setRestoreCfm(null)} icon="🔄" title="Restore Client?" desc={`Restore "${restoreCfm?.name}" back to active clients?`} cStyle="s" cLabel="Yes, Restore"
        details={[{ i: '✅', t: 'Client will be restored to active list' }]}
        onConfirm={handleRestore}
      />

      {/* Detail Modal */}
      <Modal open={!!detail && !viewOrder} onClose={() => setDetail(null)} title="" w={560}>
        {detail && (
          <>
            <div className="flex items-center gap-2.5 mb-3.5">
              <div className={`text-lg font-bold flex items-center gap-1.5 ${detail.is_vip ? 'text-gold' : 'text-t1'}`}>
                {detail.is_vip ? <Icons.Crown /> : null}{detail.name}
              </div>
              {detail.is_vip ? <VipBadge /> : null}
              <button className={`ml-auto px-2.5 py-1 rounded text-[10px] font-semibold border ${detail.is_vip ? 'bg-gradient-to-br from-gold to-or text-white border-gold' : 'border-bd text-t2'}`}
                onClick={() => handleToggleVip(detail.id)}>
                {detail.is_vip ? 'Remove VIP' : 'Make VIP'}
              </button>
            </div>
            <div className="grid grid-cols-2 gap-2 mb-3 text-xs">
              <div><span className="block text-[11px] font-semibold text-t2 mb-0.5">Phone</span>{detail.phone || '—'}</div>
              <div><span className="block text-[11px] font-semibold text-t2 mb-0.5">Email</span>{detail.email || '—'}</div>
              <div className="col-span-2"><span className="block text-[11px] font-semibold text-t2 mb-0.5">Address</span>{detail.address || '—'}</div>
              <div><span className="block text-[11px] font-semibold text-t2 mb-0.5">Date of Birth</span>{detail.birth_date ? new Date(detail.birth_date).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) : '—'}</div>
              <div><span className="block text-[11px] font-semibold text-t2 mb-0.5">Allergies</span>{detail.allergies || 'None'}</div>
              <div><span className="block text-[11px] font-semibold text-t2 mb-0.5">Client Since</span>{detail.created_at ? new Date(detail.created_at).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) : '—'}</div>
            </div>
            <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
              <div className="text-[11px] font-bold text-ac uppercase mb-2">Referral Info</div>
              {detail.referred_by ? (
                <div className="text-xs text-pr flex gap-1 items-center"><Icons.Link /> Referred by <strong>{clients.find((c) => c.id === detail.referred_by)?.name}</strong></div>
              ) : (<div className="text-xs text-t2">No referrer</div>)}
              {referredClients.length > 0 && (
                <>
                  <div className="text-[11px] font-semibold text-t2 mt-1.5 mb-1">Referred {referredClients.length} — Earned {fmt(referralEarnings(detail.id))}</div>
                  {referredClients.map((rc) => (<div key={rc.id} className="text-xs py-0.5"><Icons.Star /> {rc.name} <span className="text-pr">+$75</span></div>))}
                </>
              )}
            </div>
            <div className="bg-s2 rounded-md p-3 mb-3 border border-bd flex gap-4">
              <div><div className="text-[10px] text-t2">Total Spent</div><div className="text-lg font-bold text-gr">{fmt(clientSpent(detail.id))}</div></div>
              <div><div className="text-[10px] text-t2">Orders</div><div className="text-lg font-bold">{cO.filter((o) => o.status === 'confirmed').length}</div></div>
            </div>
            <h4 className="text-xs font-bold mb-1.5">Orders ({cO.length})</h4>
            <div className="flex gap-2 mb-2 items-center flex-wrap">
              <div className="flex items-center gap-1.5 bg-s2 border border-bd rounded-md px-2 py-1 flex-1 min-w-[150px]">
                <Icons.Search />
                <input className="bg-transparent border-none text-t1 text-[11px] w-full outline-none" placeholder="Search product, date..." value={orderSearch} onChange={(e) => setOrderSearch(e.target.value)} />
              </div>
              <select className="bg-s2 border border-bd rounded-md text-t1 text-[11px] px-2 py-1 outline-none" value={orderSort} onChange={(e) => setOrderSort(e.target.value)}>
                <option value="newest">Newest</option>
                <option value="oldest">Oldest</option>
              </select>
            </div>
            {(() => {
              let filtered = cO;
              if (orderSearch.trim()) {
                const q = orderSearch.toLowerCase();
                filtered = filtered.filter((o) => {
                  const itemNames = (o.items || []).map((i) => products.find((p) => p.id === i.product_id)?.name || '').join(' ').toLowerCase();
                  const dateStr = toLocal(o.order_date);
                  const dateFmt = fmtD(o.order_date).toLowerCase();
                  return itemNames.includes(q) || dateStr.includes(q) || dateFmt.includes(q) || o.id.toLowerCase().includes(q);
                });
              }
              if (orderSort === 'oldest') filtered = [...filtered].sort((a, b) => (a.order_date || '').localeCompare(b.order_date || ''));
              else filtered = [...filtered].sort((a, b) => (b.order_date || '').localeCompare(a.order_date || ''));
              return filtered.length === 0 ? (
                <p className="text-t2 text-xs text-center py-2">No matching orders</p>
              ) : filtered.map((o) => (
                <div key={o.id} className="p-2 px-2.5 mb-1 rounded-md bg-s2 border border-bd cursor-pointer hover:border-ac" onClick={() => setViewOrder(o)}>
                  <div className="flex justify-between items-center">
                    <div>
                      <div className="text-[13px] font-semibold">#{o.id} · {fmtD(o.order_date)} — <span className="text-gr">{fmt(o.total)}</span></div>
                      <div className="text-[11px] text-t2">{(o.items || []).map((i) => products.find((p) => p.id === i.product_id)?.name).join(', ')}</div>
                    </div>
                    <div className="flex gap-1 items-center"><Badge s={o.status} /><Icons.Eye /></div>
                  </div>
                </div>
              ));
            })()}
            <div className="flex justify-end mt-2.5">
              <button className="bg-ac text-white px-3.5 py-1.5 rounded-md text-xs font-semibold hover:bg-ac/90" onClick={() => { setDetail(null); nav('orders', detail.id); }}>+ New Order</button>
            </div>
          </>
        )}
      </Modal>

      <OrderDetailModal open={!!viewOrder} order={viewOrder} products={products} clients={clients} onClose={() => setViewOrder(null)} />

      {/* Add/Edit Modal with validation */}
      <Modal open={!!modal} onClose={() => { setModal(null); setFormErrors({}); }} title={modal === 'add' ? 'Add Client' : 'Edit Client'}>
        <Field label="Name" required error={formErrors.name}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.name || ''} onChange={(e) => setForm({ ...form, name: e.target.value })} /></Field>
        <div className="flex gap-2.5 mb-2.5">
          <Field label="Phone" required error={formErrors.phone}><PhoneInput value={form.phone || ''} onChange={(v) => setForm({ ...form, phone: v })} /></Field>
          <Field label="Email" required error={formErrors.email}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.email || ''} onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="e.g. name@email.com" /></Field>
        </div>
        <Field label="Address" required error={formErrors.address}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.address || ''} onChange={(e) => setForm({ ...form, address: e.target.value })} placeholder="Full address" /></Field>
        <Field label="Date of Birth" required error={formErrors.birth_date}><input type="date" className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={toLocal(form.birth_date)} onChange={(e) => setForm({ ...form, birth_date: e.target.value })} /></Field>
        <Field label="Allergies" required error={formErrors.allergies}><input className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px]" value={form.allergies || ''} onChange={(e) => setForm({ ...form, allergies: e.target.value })} placeholder="e.g. Penicillin, Sulfa (or None)" /></Field>
        <Field label="Notes (optional)"><textarea className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px] min-h-[40px] resize-y" value={form.notes || ''} onChange={(e) => setForm({ ...form, notes: e.target.value })} /></Field>
        <div className="flex justify-end gap-2">
          <button className="px-3.5 py-1.5 rounded-md border border-bd text-t2 text-xs font-semibold hover:bg-s2" onClick={() => { setModal(null); setFormErrors({}); }}>Cancel</button>
          <button className="bg-ac text-white px-3.5 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-ac/90" onClick={save}><Icons.Check /> Save</button>
        </div>
      </Modal>
    </div>
  );
}
