"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { SalesList, SalesReportBook, saleTotalOf, type SaleItem, type SaleRecord, type SalesQuery, type StkAttempt } from "@/components/medora/sales-lists";
import { toast } from "@/components/ui/toast";
import { TODAY } from "@/lib/mock-data";

/*
 * One deterministic set of sales for 18–20 Oct 2026 at Westlands Main, so the list and every report agree.
 * Generated from fixed rules (no randomness), so figures are the same on every load.
 */

const CATALOG: SaleItem[] = [
  { product: "Panadol 500 mg, strip", category: "Analgesics", qty: 1, price: 58, cost: 32, vat: 0 },
  { product: "Augmentin 625 mg, 14s", category: "Antibiotics", qty: 1, price: 1260, cost: 1020, vat: 0 },
  { product: "Nivea Soft cream 200 ml", category: "Dermatology", qty: 1, price: 610, cost: 455, vat: 16 },
  { product: "Vitamin C 1000 mg, 20s", category: "Vitamins", qty: 1, price: 450, cost: 300, vat: 16 },
  { product: "Calamine lotion 100 ml", category: "Dermatology", qty: 1, price: 240, cost: 160, vat: 16 },
  { product: "Metformin 500 mg, 100s", category: "Antidiabetics", qty: 1, price: 450, cost: 330, vat: 0 },
];
const METHODS = ["M-Pesa", "Cash", "M-Pesa", "Card", "Cash", "M-Pesa", "Credit"] as const;
const PEOPLE = [
  { seller: "Grace Wanjiru", cashier: "Kevin Mutua" },
  { seller: "Kevin Mutua", cashier: "Kevin Mutua" },
  { seller: "Faith Njeri", cashier: "Faith Njeri" },
];
const CUSTOMERS = ["Mary Wambui", "John Otieno", undefined, undefined, "Ali Hassan", undefined];

export const SALES: SaleRecord[] = (() => {
  const out: SaleRecord[] = [];
  const days = ["2026-10-18", "2026-10-19", "2026-10-20"];
  let n = 5150;
  days.forEach((date, d) => {
    const count = [11, 13, 14][d];
    for (let k = 0; k < count; k++) {
      n++;
      const seed = n * 7 + k;
      const p = PEOPLE[seed % PEOPLE.length];
      const items = [CATALOG[seed % CATALOG.length], CATALOG[(seed + 2) % CATALOG.length]].slice(0, 1 + (seed % 2)).map((i, j) => ({ ...i, qty: 1 + ((seed + j) % 3) }));
      const method = METHODS[seed % METHODS.length];
      const status: SaleRecord["status"] = n % 17 === 0 ? "Returned" : n % 11 === 0 ? "Part returned" : "Completed";
      const s: SaleRecord = {
        receipt: `RCP-00${n}`,
        date,
        time: `${String(8 + Math.floor((k * 9) / count)).padStart(2, "0")}:${String((seed * 13) % 60).padStart(2, "0")}`,
        branch: "Westlands Main",
        seller: p.seller,
        cashier: p.cashier,
        customer: method === "Credit" ? "Aga Khan Hospital" : CUSTOMERS[seed % CUSTOMERS.length],
        method,
        items,
        etims: d > 0 || k > 3,
        status,
        returned: 0,
        archived: n % 19 === 0,
        invoice: method === "Credit" ? `INV-2026-00${800 + (n % 50)}` : undefined,
      };
      s.returned = status === "Returned" ? saleTotalOf(s) : status === "Part returned" ? Math.round(s.items[0].price * (1 + s.items[0].vat / 100) * 100) / 100 : 0;
      out.push(s);
    }
  });
  return out.sort((a, b) => (b.date + b.time).localeCompare(a.date + a.time));
})();

const STK: StkAttempt[] = SALES.filter((s) => s.method === "M-Pesa")
  .slice(0, 9)
  .flatMap((s, i): StkAttempt[] => {
    const amt = saleTotalOf(s);
    const at = `${s.date.slice(5)} ${s.time}`;
    const phone = `07•• ••• ${String(100 + i * 37).slice(-3)}`;
    if (i === 2) return [{ checkoutId: `ws_CO_${s.receipt.slice(-4)}a`, at, receipt: s.receipt, phone, amount: amt, result: "Cancelled by customer" as const }, { checkoutId: `ws_CO_${s.receipt.slice(-4)}b`, at, receipt: s.receipt, phone, amount: amt, result: "Paid" as const, mpesaRef: `SJK${i}A${s.receipt.slice(-3)}Q` }];
    if (i === 5) return [{ checkoutId: `ws_CO_${s.receipt.slice(-4)}a`, at, receipt: s.receipt, phone, amount: amt, result: "Timed out, paid on check" as const, mpesaRef: `SJK${i}B${s.receipt.slice(-3)}R` }];
    if (i === 7) return [{ checkoutId: `ws_CO_${s.receipt.slice(-4)}a`, at, receipt: s.receipt, phone, amount: amt, result: "Timed out, not paid" as const }, { checkoutId: `ws_CO_${s.receipt.slice(-4)}b`, at, receipt: s.receipt, phone, amount: amt, result: "Paid" as const, mpesaRef: `SJK${i}C${s.receipt.slice(-3)}T` }];
    return [{ checkoutId: `ws_CO_${s.receipt.slice(-4)}a`, at, receipt: s.receipt, phone, amount: amt, result: "Paid" as const, mpesaRef: `SJK${i}D${s.receipt.slice(-3)}W` }];
  });

/** Stand-in for the API: filters and pages on the "server" and answers after a short delay. */
async function fetchSalesPage(q: SalesQuery) {
  await new Promise((r) => setTimeout(r, 450));
  const term = q.q.trim().toLowerCase();
  const all = SALES.filter((s) => !s.archived && s.date >= q.from && s.date <= q.to && (!q.seller || s.seller === q.seller) && (!q.cashier || s.cashier === q.cashier) && (!term || `${s.receipt} ${s.customer ?? ""}`.toLowerCase().includes(term)));
  return { rows: all.slice((q.page - 1) * q.pageSize, q.page * q.pageSize), total: all.length, totalValue: Math.round(all.reduce((t, s) => t + saleTotalOf(s), 0) * 100) / 100 };
}

export function SalesListSection() {
  return (
    <Section id="sales-list" title="Sales list" description="PS-22: opens on today, filters by date, seller and cashier, and pages through the server ten at a time; it never loads every sale. Export asks the server for all matching sales as a file.">
      <Example title="Sales, Westlands Main" description="Today has 13 sales over two pages (one more was archived). Widen the dates to 18 Oct, or filter by seller">
        <SalesList
          today={TODAY}
          sellers={["Faith Njeri", "Grace Wanjiru", "Kevin Mutua"]}
          cashiers={["Faith Njeri", "Kevin Mutua"]}
          fetchPage={fetchSalesPage}
          onOpen={(r) => toast.add({ title: `Opens ${r}` })}
          onExport={(q, n) => toast.add({ title: `Exporting ${n} sales`, description: `${q.from} to ${q.to}. You'll get the file when the server has built it.` })}
        />
      </Example>
    </Section>
  );
}

export function SalesReportBookSection() {
  const [sales, setSales] = React.useState(SALES);
  return (
    <Section id="sales-report-book" title="Sales reports" description="RP-06 and RP-07: the eight existing sales tabs and the eleven new reports, chosen from one list. Every report is built from the same sale records, so their totals agree; archived sales are left out until restored.">
      <Example title="Sales reports, Westlands Main" description="18–20 Oct 2026. Try Archived sales and restore one: it reappears in the others">
        <SalesReportBook
          sales={sales}
          stk={STK}
          period="18–20 Oct 2026, Westlands Main"
          onRestore={(r) => {
            setSales((xs) => xs.map((s) => (s.receipt === r ? { ...s, archived: false } : s)));
            toast.add({ title: `${r} restored`, description: "Back in sales history and every total." });
          }}
        />
      </Example>
    </Section>
  );
}
