// Customers — scoped to the current workspace.
function CustomersPage() {
  const auth = useAuth();
  const ws = auth.currentWorkspace;
  const toast = useToast();

  const [customers, setCustomers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [query, setQuery] = useState("");
  const [tag, setTag] = useState("all");
  const [selected, setSelected] = useState(null);
  const [showAdd, setShowAdd] = useState(false);

  const load = useCallback(async () => {
    if (!ws?.id) return;
    setLoading(true); setError(null);
    const res = await SB.from('customers')
      .select('*')
      .eq('workspace_id', ws.id)
      .order('created_at', { ascending: false });
    setLoading(false);
    if (res.error) { setError(res.error.message); return; }
    setCustomers(res.data || []);
  }, [ws?.id]);

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

  const allTags = Array.from(new Set(customers.flatMap(c => c.tags || [])));
  const filtered = customers.filter((c) => {
    if (tag !== "all" && !(c.tags || []).includes(tag)) return false;
    if (query) {
      const q = query.toLowerCase();
      const blob = `${c.name} ${c.email} ${c.phone || ''}`.toLowerCase();
      if (!blob.includes(q)) return false;
    }
    return true;
  });

  const thirtyDaysAgo = new Date(); thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
  const newRecently = customers.filter(c => new Date(c.created_at) > thirtyDaysAgo).length;

  return (
    <div className="px-5 lg:px-7 py-7 max-w-[1500px] mx-auto">
      <PageHeader
        eyebrow="People"
        title="Customers"
        subtitle="Booking history, contact info, and internal notes."
        actions={
          <Button icon="user-plus" onClick={() => setShowAdd(true)}>Add customer</Button>
        }
      />

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-6">
        <StatCard label="Total customers" value={customers.length} hint="All-time" />
        <StatCard label="VIPs" value={customers.filter(c => (c.tags || []).includes("VIP")).length} hint="Tagged accounts" />
        <StatCard label="Repeat customers" value={customers.filter(c => (c.bookings_count || 0) > 2).length} hint="3+ bookings" />
        <StatCard label="New (last 30 days)" value={newRecently} hint="First-time bookings" />
      </div>

      <div className="flex flex-wrap items-center gap-3 mb-4">
        <div className="flex items-center gap-2 bg-ink/[0.02] border border-ink/[0.06] rounded-md px-2.5 h-9 w-full sm:w-80">
          <Icon name="search" size={13} className="text-ink/40" />
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search name, email, phone" className="bg-transparent flex-1 text-[13px] placeholder-ink/35 outline-none" />
        </div>
        <div className="flex items-center gap-1.5 flex-wrap">
          <button onClick={() => setTag("all")} className={`h-7 px-2.5 rounded-full text-[11.5px] ${tag === "all" ? "bg-ink text-white" : "bg-white hover:bg-ink/[0.05] text-ink/75"}`}>All</button>
          {allTags.map(t => (
            <button key={t} onClick={() => setTag(t)} className={`h-7 px-2.5 rounded-full text-[11.5px] ${tag === t ? "bg-ink text-white" : "bg-white hover:bg-ink/[0.05] text-ink/75"}`}>{t}</button>
          ))}
        </div>
        <div className="ml-auto text-[12px] text-ink/55">{filtered.length} of {customers.length}</div>
      </div>

      {loading ? (
        <div className="py-16 text-center text-[12.5px] text-ink/50">Loading customers…</div>
      ) : error ? (
        <div className="py-16 text-center text-[12.5px] text-danger">Couldn't load customers: {error}</div>
      ) : customers.length === 0 ? (
        <div className="rounded-lg border border-dashed border-ink/[0.12] bg-white p-12 text-center">
          <div className="font-display text-[20px] mb-1">No customers yet</div>
          <p className="text-[13px] text-ink/55 mb-5 max-w-md mx-auto">
            Customers are added automatically when someone books through your public page. You can also add them manually.
          </p>
          <Button icon="user-plus" onClick={() => setShowAdd(true)}>Add a customer</Button>
        </div>
      ) : (
        <div className="rounded-lg border border-ink/[0.06] bg-ink/[0.015] overflow-hidden">
          <table className="w-full text-[13px]">
            <thead className="text-[11px] uppercase tracking-[0.08em] text-ink/45 bg-white">
              <tr className="border-b border-ink/[0.06]">
                <th className="text-left font-medium px-5 py-3">Customer</th>
                <th className="text-left font-medium px-2 py-3 hidden md:table-cell">Phone</th>
                <th className="text-left font-medium px-2 py-3">Tags</th>
                <th className="text-left font-medium px-2 py-3 hidden lg:table-cell">Bookings</th>
                <th className="text-left font-medium px-2 py-3 hidden lg:table-cell">Events</th>
                <th className="text-left font-medium px-2 py-3 hidden md:table-cell">Last seen</th>
                <th className="px-5"></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((c) => (
                <tr key={c.id} onClick={() => setSelected(c)} className="border-b border-ink/[0.04] hover:bg-white cursor-pointer">
                  <td className="px-5 py-3">
                    <div className="flex items-center gap-3">
                      <Avatar name={c.name} size={32} />
                      <div className="min-w-0">
                        <div className="font-medium">{c.name}</div>
                        <div className="text-[11.5px] text-ink/50 truncate">{c.email}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-2 py-3 text-ink/75 font-mono text-[12px] hidden md:table-cell">{c.phone || "—"}</td>
                  <td className="px-2 py-3">
                    <div className="flex items-center gap-1.5 flex-wrap">
                      {(c.tags || []).map(t => <Badge key={t} tone={t === "VIP" ? "accent" : t === "New" ? "ok" : "neutral"}>{t}</Badge>)}
                    </div>
                  </td>
                  <td className="px-2 py-3 hidden lg:table-cell">{c.bookings_count || 0}</td>
                  <td className="px-2 py-3 hidden lg:table-cell">{c.events_count || 0}</td>
                  <td className="px-2 py-3 text-ink/65 hidden md:table-cell">{c.last_seen_at ? relTime(new Date(c.last_seen_at)) : "—"}</td>
                  <td className="px-5 py-3 text-right">
                    <button className="text-ink/55 hover:text-ink p-1"><Icon name="chevron-right" size={14} /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <CustomerDrawer customer={selected} onClose={() => setSelected(null)} onChanged={load} />
      <AddCustomerModal open={showAdd} onClose={() => setShowAdd(false)} onCreated={(c) => { setCustomers([c].concat(customers)); setShowAdd(false); toast.push(`Added ${c.name}`); }} workspaceId={ws?.id} />
    </div>
  );
}

function CustomerDrawer({ customer, onClose, onChanged }) {
  const [bookings, setBookings] = useState([]);
  const [notes, setNotes] = useState("");
  const [saving, setSaving] = useState(false);
  const toast = useToast();

  useEffect(() => {
    if (!customer) return;
    setNotes(customer.notes || "");
    (async () => {
      const res = await SB.from('bookings')
        .select('id, starts_at, duration_min, status, form_id, forms(public_title)')
        .eq('customer_id', customer.id)
        .order('starts_at', { ascending: false });
      setBookings(res.data || []);
    })();
  }, [customer?.id]);

  const saveNotes = async () => {
    if (!customer) return;
    setSaving(true);
    const res = await SB.from('customers').update({ notes }).eq('id', customer.id);
    setSaving(false);
    if (res.error) { toast.push("Couldn't save notes: " + res.error.message); return; }
    toast.push("Notes saved");
    if (onChanged) onChanged();
  };

  if (!customer) return null;
  const tags = customer.tags || [];

  return (
    <Drawer
      open={!!customer}
      onClose={onClose}
      subtitle="Customer profile"
      title={customer.name}
      width={560}
      actions={<Button onClick={saveNotes} disabled={saving} icon="check">{saving ? "Saving…" : "Save"}</Button>}
    >
      <div className="flex items-center gap-4 pb-5 border-b border-ink/[0.06]">
        <Avatar name={customer.name} size={52} />
        <div className="flex-1 min-w-0">
          <div className="text-[12.5px] text-ink/55">{customer.email}</div>
          <div className="text-[12.5px] text-ink/55 font-mono">{customer.phone || "—"}</div>
          {tags.length > 0 && (
            <div className="flex items-center gap-1.5 mt-2 flex-wrap">
              {tags.map(t => <Badge key={t} tone={t === "VIP" ? "accent" : t === "New" ? "ok" : "neutral"}>{t}</Badge>)}
            </div>
          )}
        </div>
      </div>

      <div className="grid grid-cols-3 gap-3 pt-4">
        <SmallStat label="Bookings" value={customer.bookings_count || 0} />
        <SmallStat label="Events" value={customer.events_count || 0} />
        <SmallStat label="Last seen" value={customer.last_seen_at ? relTime(new Date(customer.last_seen_at)) : "—"} />
      </div>

      <div className="mt-5">
        <div className="text-[11px] uppercase tracking-[0.1em] text-ink/45 mb-2">Internal note</div>
        <Textarea value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Notes visible only to your team…" />
      </div>

      <div className="mt-6">
        <div className="text-[11px] uppercase tracking-[0.1em] text-ink/45 mb-2">Booking history</div>
        {bookings.length === 0 ? (
          <div className="text-[12.5px] text-ink/55">No bookings yet.</div>
        ) : (
          <div className="rounded-md border border-ink/[0.06] divide-y divide-ink/[0.06]">
            {bookings.map(b => {
              const start = new Date(b.starts_at);
              return (
                <div key={b.id} className="px-3 py-2.5 flex items-center gap-3">
                  <div className="font-mono text-[11px] text-ink/55 w-20">{fmt(start, "MMM d")}</div>
                  <div className="flex-1 min-w-0">
                    <div className="text-[13px] truncate">{b.forms?.public_title || "Booking"}</div>
                    <div className="text-[11px] text-ink/55">{fmt(start, "h:mma").toLowerCase()} · {b.duration_min}min</div>
                  </div>
                  <StatusBadge status={b.status} />
                </div>
              );
            })}
          </div>
        )}
      </div>
    </Drawer>
  );
}

// Lightweight "Add customer" modal — direct insert into the workspace.
function AddCustomerModal({ open, onClose, onCreated, workspaceId }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (open) { setName(""); setEmail(""); setPhone(""); setBusy(false); setError(null); }
  }, [open]);

  const canSubmit = name.trim().length >= 2 && /^.+@.+\..+$/.test(email.trim()) && !busy;

  const submit = async () => {
    setBusy(true); setError(null);
    const res = await SB.from('customers')
      .insert({
        workspace_id: workspaceId,
        name: name.trim(),
        email: email.trim().toLowerCase(),
        phone: phone.trim() || null
      })
      .select()
      .single();
    setBusy(false);
    if (res.error) {
      setError(res.error.code === '23505'
        ? `A customer with that email already exists.`
        : res.error.message);
      return;
    }
    onCreated(res.data);
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Add customer"
      subtitle="They'll be deduped by email within this workspace."
      width={500}
      actions={
        <>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Cancel</Button>
          <Button icon="check" onClick={submit} disabled={!canSubmit}>{busy ? "Adding…" : "Add customer"}</Button>
        </>
      }
    >
      <div className="flex flex-col gap-4">
        <Field label="Full name" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Marcus Whitfield" autoFocus />
        </Field>
        <Field label="Email" required>
          <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="marcus@example.com" />
        </Field>
        <Field label="Phone">
          <Input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+32 …" />
        </Field>
        {error && (
          <div className="text-[12px] text-danger bg-danger/[0.06] border border-danger/15 rounded-md px-3 py-2">{error}</div>
        )}
      </div>
    </Modal>
  );
}

function SmallStat({ label, value }) {
  return (
    <div className="rounded-md border border-ink/[0.06] bg-white p-3">
      <div className="text-[10.5px] uppercase tracking-[0.1em] text-ink/45">{label}</div>
      <div className="font-display text-[20px] leading-none mt-1.5">{value}</div>
    </div>
  );
}

Object.assign(window, { CustomersPage });
