"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { BankConnections, LeaveTypes, MpesaBranchKeys, PartyOpeningBalances, type BankLink, type LeaveType, type MpesaBranch, type PartyOpening } from "@/components/medora/setup-more";
import { toast } from "@/components/ui/toast";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";

/* ------------------------------------ AC-06 ------------------------------------ */

const CUSTOMERS = [
  { id: 7, name: "Aga Khan Hospital" },
  { id: 12, name: "Nairobi West Clinic" },
  { id: 5, name: "John Otieno" },
  { id: 2, name: "Mary Wambui" },
];
const SUPPLIERS = [
  { id: 1, name: "Harleys Ltd" },
  { id: 2, name: "Dawa Ltd" },
  { id: 3, name: "Cosmos Ltd" },
  { id: 4, name: "Surgipharm" },
];

export function PartyOpeningSection() {
  const [kind, setKind] = React.useState<"customer" | "supplier">("customer");
  const [cust, setCust] = React.useState<Record<number, PartyOpening>>({
    7: { amount: "48,200", ref: "OLD-2291", dated: "2026-08-14", due: "2026-09-13" },
    12: { amount: "4,000", ref: "OLD-2307", dated: "2026-08-29", due: "2026-08-20" },
  });
  const [supp, setSupp] = React.useState<Record<number, PartyOpening>>({
    1: { amount: "80,100", ref: "HL-86120", dated: "2026-08-31", due: "2026-09-30" },
  });
  return (
    <Section id="party-opening" title="Opening balances for customers and suppliers" description="AC-06: what each customer owed, and what was owed to each supplier, on the day before Medora starts, typed in or imported from a CSV. Each becomes an opening invoice or bill that ages from its own date; the other side is Opening balance equity, so the ledger balances.">
      <Example title="Opening balances as at 31 Aug 2026" description="Nairobi West Clinic's due date is before its invoice date: fix it. The ledger entry follows the total">
        <div className="mb-3">
          <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Whose balances" value={[kind]} onValueChange={(v: string[]) => v[0] && setKind(v[0] as typeof kind)}>
            <ToggleGroupItem value="customer">Customers</ToggleGroupItem>
            <ToggleGroupItem value="supplier">Suppliers</ToggleGroupItem>
          </ToggleGroup>
        </div>
        {kind === "customer" ? (
          <PartyOpeningBalances key="c" kind="customer" parties={CUSTOMERS} asAt="2026-08-31" lines={cust} onChange={(id, l) => setCust((x) => ({ ...x, [id]: l }))} />
        ) : (
          <PartyOpeningBalances key="s" kind="supplier" parties={SUPPLIERS} asAt="2026-08-31" lines={supp} onChange={(id, l) => setSupp((x) => ({ ...x, [id]: l }))} />
        )}
      </Example>
    </Section>
  );
}

/* ------------------------------------ HR-04 ------------------------------------ */

export function LeaveTypesSection() {
  const [types, setTypes] = React.useState<LeaveType[]>([
    { id: "a", name: "Annual", days: "21", carryMax: "5", paid: true, document: false, appliesTo: "All staff" },
    { id: "s", name: "Sick", days: "14", carryMax: "", paid: true, document: true, appliesTo: "All staff" },
    { id: "m", name: "Maternity", days: "90", carryMax: "", paid: true, document: true, appliesTo: "Women" },
    { id: "p", name: "Paternity", days: "14", carryMax: "", paid: true, document: true, appliesTo: "Men" },
    { id: "c", name: "Compassionate", days: "5", carryMax: "10", paid: true, document: false, appliesTo: "Permanent only" },
    { id: "u", name: "Unpaid", days: "30", carryMax: "", paid: false, document: false, appliesTo: "All staff" },
  ]);
  return (
    <Section id="leave-types" title="Leave types and allocations" description="HR-04: each leave type's yearly days, how much rolls over, whether it's paid, whether it needs a document, and who it applies to. The preview shows what one employee gets this year, carry-over included.">
      <Example title="Leave types" description="Compassionate allows more carry-over than its yearly days: fix it">
        <LeaveTypes types={types} onChange={setTypes} preview={{ name: "Faith Njeri", kind: "Permanent", gender: "Woman", leftLastYear: { Annual: 8, Compassionate: 2 } }} />
      </Example>
    </Section>
  );
}

/* ------------------------------------ IG-03 ------------------------------------ */

export function MpesaKeysSection() {
  const [branches, setBranches] = React.useState<MpesaBranch[]>([
    { branch: "Westlands Main", type: "Paybill", shortcode: "512330", till: "", keys: { set: true, lastChanged: { at: "12 Sep 2026", by: "Grace Wanjiru" } }, passkey: { set: true, lastChanged: { at: "12 Sep 2026", by: "Grace Wanjiru" } }, lastTest: { ok: true, at: "20 Oct, 14:20" } },
    { branch: "Kilimani", type: "Till (Buy Goods)", shortcode: "880211", till: "880211", keys: { set: true, lastChanged: { at: "3 Oct 2026", by: "Grace Wanjiru" } }, passkey: { set: true }, lastTest: { ok: false, at: "20 Oct, 09:02", note: "Wrong passkey for this shortcode" } },
    { branch: "Nyali", type: "Till (Buy Goods)", shortcode: "774120", till: "", keys: { set: false }, passkey: { set: false } },
  ]);
  return (
    <Section id="mpesa-keys" title="M-Pesa keys per branch" description="IG-03 and ST-18: each branch's shortcode, till and keys, so one branch's payments never land in another's till. Keys are write-only: replaced, never shown, and saved only when you press Save. The callback URL comes from the server and is shown so it can be registered on Daraja.">
      <Example title="Integrations, M-Pesa (Daraja)" description="Nyali isn't set up yet; Kilimani's last test failed. Open a branch to see its keys">
        <MpesaBranchKeys
          branches={branches}
          onChange={setBranches}
          environment="Live"
          callbackUrl="https://pharmacy-api.devke.co.ke/api/sales/mpesa/callback"
          onTest={(b) => {
            setBranches((xs) => xs.map((x) => (x.branch === b ? { ...x, lastTest: { ok: true, at: "just now" } } : x)));
            toast.add({ title: `${b}: connected to M-Pesa` });
          }}
        />
      </Example>
    </Section>
  );
}

/* ------------------------------------ IG-18 ------------------------------------ */

export function BankConnectionsSection() {
  const [links, setLinks] = React.useState<BankLink[]>([
    { bank: "Equity Bank", account: "0120 2934 1188", ledger: "1040 Equity Bank", api: true, connected: true, lastSync: "20 Oct, 06:00" },
    { bank: "KCB", account: "1180 553 902", ledger: "1045 KCB", api: true, connected: false, error: "the bank's consent expired on 15 Oct" },
    { bank: "Co-operative Bank", account: "0112 4467 8890", ledger: "1050 Co-op Bank", api: false, connected: false },
  ]);
  return (
    <Section id="bank-connections" title="Bank connections" description="IG-18: a direct connection per bank account where the bank offers one, so statement lines arrive by themselves for reconciliation. Connecting goes through the bank's own sign-in; Medora never sees a banking password. Banks without an API import statements as CSV.">
      <Example title="Integrations, banks" description="KCB's consent has expired: reconnect it. Co-op Bank has no API">
        <BankConnections
          links={links}
          onConnect={(a) => {
            setLinks((xs) => xs.map((x) => (x.account === a ? { ...x, connected: true, error: undefined, lastSync: "just now" } : x)));
            toast.add({ title: "Connected", description: "Opened the bank's sign-in; statement lines will sync daily." });
          }}
          onDisconnect={(a) => setLinks((xs) => xs.map((x) => (x.account === a ? { ...x, connected: false, lastSync: undefined } : x)))}
          onImport={() => toast.add({ title: "Opens statement import in Accounts, Reconcile" })}
        />
      </Example>
    </Section>
  );
}
