"use client";

import * as React from "react";
import { ChevronRightIcon } from "lucide-react";

import { kes } from "@/components/medora/payroll";
import { Button } from "@/components/ui/button";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { cn } from "@/lib/utils";

/*
 * Customer reports (RP-09): top customers by what they spend, how often they come and what they owe, each
 * opening to their recent purchases, with a link to the full statement in Accounts. Walk-in sales aren't a
 * customer and are shown as one line so the totals still reconcile with sales.
 */

export type CustomerPurchase = { ref: string; date: string; items: number; total: number };
export type CustomerStat = { id: number; name: string; group?: string; spend: number; visits: number; balance: number; lastVisit: string; purchases: CustomerPurchase[] };

export function TopCustomers({ customers, walkIn, period, onStatement }: { customers: CustomerStat[]; walkIn: { spend: number; visits: number }; period: string; onStatement: (id: number) => void }) {
  const [sort, setSort] = React.useState<"spend" | "visits" | "balance">("spend");
  const [open, setOpen] = React.useState<number | null>(null);
  const rows = [...customers].sort((a, b) => b[sort] - a[sort]);
  const named = customers.reduce((s, c) => s + c.spend, 0);
  const all = named + walkIn.spend;
  return (
    // One container (data table spec §1): the toolbar sits inside it, above the table
    <div className="overflow-hidden rounded-md border border-[var(--color-border-panel)] bg-card">
      <div className="flex flex-wrap items-center justify-between gap-2 border-b border-[var(--color-border-subtle)] p-3">
        <p className="text-sm">
          {period}: named customers spent <strong className="tabular-nums">{kes(named)}</strong>, {((named / all) * 100).toFixed(1)}% of sales.
        </p>
        <NativeSelect aria-label="Sort by" value={sort} onChange={(e) => setSort(e.target.value as typeof sort)}>
          <NativeSelectOption value="spend">Most spent</NativeSelectOption>
          <NativeSelectOption value="visits">Most visits</NativeSelectOption>
          <NativeSelectOption value="balance">Most owed</NativeSelectOption>
        </NativeSelect>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full min-w-[700px] text-sm">
          <thead className="bg-[var(--color-bg-surface-subtle)] text-left text-xs text-muted-foreground">
            <tr>
              <th className="w-8" />
              <th className="px-2 py-2 font-medium">Customer</th>
              <th className="px-2 py-2 text-right font-medium">Spent</th>
              <th className="px-2 py-2 text-right font-medium">Visits</th>
              <th className="px-2 py-2 text-right font-medium">Average basket</th>
              <th className="px-2 py-2 text-right font-medium">Owes</th>
              <th className="px-2 py-2 font-medium">Last visit</th>
            </tr>
          </thead>
          {rows.map((c, i) => (
            <tbody key={c.id} className="border-t border-[var(--color-border-subtle)]">
              <tr className={cn(open === c.id && "bg-muted/30")}>
                <td className="px-1 py-2">
                  <Button size="icon-sm" variant="ghost" aria-expanded={open === c.id} aria-label={`${open === c.id ? "Hide" : "Show"} ${c.name}'s purchases`} onClick={() => setOpen(open === c.id ? null : c.id)}>
                    <ChevronRightIcon className={cn("transition-transform", open === c.id && "rotate-90")} />
                  </Button>
                </td>
                <td className="px-2 py-2">
                  <span className="mr-1.5 text-xs text-muted-foreground tabular-nums">{i + 1}.</span>
                  <span className="font-medium">{c.name}</span>
                  {c.group ? <span className="block text-xs text-muted-foreground">{c.group}</span> : null}
                </td>
                <td className="px-2 py-2 text-right tabular-nums">{kes(c.spend)}</td>
                <td className="px-2 py-2 text-right tabular-nums">{c.visits}</td>
                <td className="px-2 py-2 text-right tabular-nums">{kes(c.spend / c.visits)}</td>
                <td className={cn("px-2 py-2 text-right tabular-nums", c.balance > 0 && "font-medium")}>{c.balance ? kes(c.balance) : "–"}</td>
                <td className="px-2 py-2 text-xs whitespace-nowrap">{c.lastVisit}</td>
              </tr>
              {open === c.id ? (
                <tr>
                  <td />
                  <td colSpan={6} className="px-2 pb-3">
                    <ul className="space-y-0.5 text-xs">
                      {c.purchases.map((p) => (
                        <li key={p.ref} className="flex justify-between gap-3">
                          <span>
                            <span className="font-mono">{p.ref}</span> · {p.date} · {p.items} {p.items === 1 ? "item" : "items"}
                          </span>
                          <span className="tabular-nums">{kes(p.total)}</span>
                        </li>
                      ))}
                    </ul>
                    <Button size="sm" variant="link" className="mt-1 px-0" onClick={() => onStatement(c.id)}>
                      Open {c.name}&apos;s statement
                    </Button>
                  </td>
                </tr>
              ) : null}
            </tbody>
          ))}
          <tbody className="border-t border-[var(--color-border-subtle)] text-muted-foreground">
            <tr>
              <td />
              <td className="px-2 py-2">Walk-in sales (no customer named)</td>
              <td className="px-2 py-2 text-right tabular-nums">{kes(walkIn.spend)}</td>
              <td className="px-2 py-2 text-right tabular-nums">{walkIn.visits.toLocaleString("en-US")}</td>
              <td className="px-2 py-2 text-right tabular-nums">{kes(walkIn.spend / walkIn.visits)}</td>
              <td colSpan={2} />
            </tr>
          </tbody>
          <tfoot className="border-t-2 border-[var(--color-border-panel)] bg-muted/30 font-semibold">
            <tr>
              <td />
              <td className="px-2 py-2">All sales</td>
              <td className="px-2 py-2 text-right tabular-nums">{kes(all)}</td>
              <td className="px-2 py-2 text-right tabular-nums">{(customers.reduce((s, c) => s + c.visits, 0) + walkIn.visits).toLocaleString("en-US")}</td>
              <td colSpan={3} />
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  );
}
