"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { ComplaintThread, LoyaltyLedger, LoyaltyRuleForm, MedicalEntryForm, MedicalTimeline, SchemeCard, SupplierPrices, type ComplaintCase, type LoyaltyRule, type MedicalEntry, type PointsEntry, type SchemeMember } from "@/components/medora/parties-ops";
import { SensitiveNotice } from "@/components/medora/sensitive";
import { Button } from "@/components/ui/button";
import { Field, FieldError, FieldLabel } from "@/components/ui/field";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "@/components/ui/toast";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { formatDate, TODAY } from "@/lib/mock-data";

const fd = (d: string) => formatDate(d);

const MEMBERS: Record<string, SchemeMember> = {
  active: { scheme: "AAR Insurance, Outpatient Gold", memberNo: "AAR-449120-01", relation: "Principal", limit: 60000, used: 21400, copayPct: 10, validUntil: "2027-03-31", status: "Active" },
  low: { scheme: "Jubilee Health, Family Silver", memberNo: "JUB-77013-03", relation: "Child", principal: "John Otieno", limit: 20000, used: 19300, copayPct: 0, validUntil: "2026-12-31", status: "Active" },
  expired: { scheme: "Madison, Corporate", memberNo: "MAD-20441-01", relation: "Principal", limit: 40000, used: 8000, copayPct: 20, validUntil: "2026-09-30", status: "Expired" },
};

function SchemeDemo() {
  const [which, setWhich] = React.useState("active");
  return (
    <Example title="Insurance scheme membership" description="Bill KES 2,450.00. Co-pay first, then the scheme up to what's left; an expired member pays in full">
      <div className="space-y-3">
        <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Member" value={[which]} onValueChange={(v: string[]) => v[0] && setWhich(v[0])}>
          <ToggleGroupItem value="active">Active</ToggleGroupItem>
          <ToggleGroupItem value="low">Cover nearly used</ToggleGroupItem>
          <ToggleGroupItem value="expired">Expired</ToggleGroupItem>
        </ToggleGroup>
        <SchemeCard member={MEMBERS[which]} bill={2450} formatDate={fd} />
      </div>
    </Example>
  );
}

const POINTS: PointsEntry[] = [
  { id: "p1", date: "2026-07-02", kind: "Earned", points: 420, ref: "SALE-004812" },
  { id: "p2", date: "2026-08-14", kind: "Earned", points: 610, ref: "SALE-005010" },
  { id: "p3", date: "2026-09-03", kind: "Redeemed", points: -300, ref: "SALE-005077", note: "KES 300.00 off" },
  { id: "p4", date: "2026-10-01", kind: "Expired", points: -40, ref: "AUTO", note: "Earned in Oct 2025, unused for 12 months" },
  { id: "p5", date: "2026-10-18", kind: "Earned", points: 550, ref: "SALE-005188" },
];

const MEDICAL: MedicalEntry[] = [
  { id: "m1", kind: "Allergy", date: "2023-05-12", by: "Grace Wanjiru", text: "Penicillin: rash and swelling.", severity: "Severe" },
  { id: "m2", kind: "Diagnosis", date: "2025-02-20", by: "Dr. A. Otieno", text: "Type 2 diabetes, on metformin 500 mg twice daily." },
  {
    id: "m3",
    kind: "Lab result",
    date: "2026-10-10",
    by: "Lancet Labs",
    lab: "HbA1c and lipids",
    values: [
      { test: "HbA1c", value: 7.9, unit: "%", low: 4, high: 6.5 },
      { test: "Total cholesterol", value: 4.6, unit: "mmol/L", low: 0, high: 5.2 },
      { test: "HDL", value: 0.9, unit: "mmol/L", low: 1, high: 3 },
    ],
  },
  { id: "m4", kind: "Sick-off note", date: "2026-10-12", by: "Grace Wanjiru", from: "2026-10-12", to: "2026-10-14", reason: "Acute gastroenteritis" },
];

function CustomerRecordsDemo() {
  const [rule, setRule] = React.useState<LoyaltyRule>({ kesPerPoint: 100, pointValue: 1, block: 100, expiryMonths: 12, excludeRx: true });
  const [medical, setMedical] = React.useState(MEDICAL);
  const [adding, setAdding] = React.useState(false);
  return (
    <>
      <Example title="Loyalty rule (Settings)" description="How points are earned and what they're worth, with the effective discount on a typical basket. Try 1 point per KES 20">
        <LoyaltyRuleForm rule={rule} onChange={setRule} />
      </Example>
      <div className="grid gap-4 lg:grid-cols-2">
        <Example title="Loyalty account" description="Every earn, redeem and expiry with a running balance">
          <LoyaltyLedger
            entries={POINTS}
            rule={`1 point per KES ${rule.kesPerPoint} spent · 1 point = KES ${rule.pointValue} · points expire after ${rule.expiryMonths} months${rule.excludeRx ? " · none on prescription medicines" : ""}`}
            expiring={{ points: 380, on: "2026-11-30" }}
            formatDate={fd}
          />
        </Example>
        <Example title="Medical records" description="Pharmacist and above only; access is logged. Severe allergies also warn at the till">
          <div className="space-y-3">
            <SensitiveNotice kind="medical" />
            {adding ? (
              <div className="rounded-lg border border-[var(--color-border-panel)] p-3">
                <MedicalEntryForm
                  by="Grace Wanjiru"
                  today={TODAY}
                  onSave={(e) => {
                    setMedical((xs) => [...xs, e]);
                    setAdding(false);
                    toast.add({ title: `${e.kind} added to Mary Wambui's record` });
                  }}
                />
              </div>
            ) : (
              <Button size="sm" variant="outline" onClick={() => setAdding(true)}>
                Add to record
              </Button>
            )}
            <MedicalTimeline entries={medical} formatDate={fd} />
          </div>
        </Example>
      </div>
    </>
  );
}

const CASE: ComplaintCase = {
  ref: "CMP-2026-0019",
  title: "Charged twice for one M-Pesa payment",
  customer: "Faith Njeri",
  sale: "SALE-005171",
  category: "Billing",
  opened: "2026-10-15",
  due: "2026-10-18",
  status: "In progress",
  assignee: "Peter Kamau",
  notes: [
    { id: "n1", at: "15 Oct, 10:12", by: "Kevin Mutua", text: "Customer says KES 1,840 left her M-Pesa twice for one basket." },
    { id: "n2", at: "15 Oct, 10:15", by: "Kevin Mutua", text: "Assigned to Peter Kamau.", kind: "status" },
    { id: "n3", at: "16 Oct, 09:40", by: "Peter Kamau", text: "Statement shows two confirmations, QJK7XYZ12 and QJK7XYZ19. Second one has no sale." },
  ],
};

function ComplaintDemo() {
  const [c, setC] = React.useState(CASE);
  const [note, setNote] = React.useState("");
  const [resolving, setResolving] = React.useState(false);
  const [tried, setTried] = React.useState(false);
  const add = (text: string, kind?: "status") => setC((x) => ({ ...x, notes: [...x.notes, { id: `n${x.notes.length + 1}`, at: "20 Oct, 14:32", by: "Grace Wanjiru", text, kind }] }));
  const open = c.status === "Open" || c.status === "In progress";
  return (
    <Example title={`Complaint ${c.ref}: ${c.title}`} description="Owner and due date up front; notes and status changes in one thread; resolving needs a resolution" bare>
      <div className="space-y-3 p-4">
        <ComplaintThread c={c} today={TODAY} formatDate={fd} />
        {open ? (
          <div className="space-y-2">
            <Field data-invalid={tried && resolving && !note.trim()}>
              <FieldLabel htmlFor="cmp-note">{resolving ? "How was it resolved?" : "Add a note"}</FieldLabel>
              <Textarea id="cmp-note" rows={2} value={note} onChange={(e) => setNote(e.target.value)} aria-invalid={tried && resolving && !note.trim()} />
              {tried && resolving && !note.trim() ? <FieldError>Say what was done, so the customer and the next person can see it.</FieldError> : null}
            </Field>
            <div className="flex flex-wrap items-center gap-2">
              <NativeSelect size="sm" aria-label="Owner" value={c.assignee} onChange={(e) => (setC({ ...c, assignee: e.target.value }), add(`Reassigned to ${e.target.value}.`, "status"))}>
                {["Peter Kamau", "Grace Wanjiru", "Kevin Mutua"].map((p) => (
                  <NativeSelectOption key={p}>{p}</NativeSelectOption>
                ))}
              </NativeSelect>
              <div className="ml-auto flex gap-2">
                <Button
                  size="sm"
                  variant={resolving ? "ghost" : "outline"}
                  onClick={() => {
                    if (resolving) {
                      setResolving(false);
                      return;
                    }
                    if (note.trim()) {
                      add(note.trim());
                      setNote("");
                    }
                  }}
                >
                  {resolving ? "Back" : "Add note"}
                </Button>
                <Button
                  size="sm"
                  onClick={() => {
                    if (!resolving) return setResolving(true);
                    setTried(true);
                    if (!note.trim()) return;
                    setC((x) => ({ ...x, status: "Resolved", resolution: note.trim() }));
                    add("Marked resolved.", "status");
                    setNote("");
                    toast.add({ title: `${c.ref} resolved`, description: "The customer gets an SMS asking to confirm before it's closed." });
                  }}
                >
                  {resolving ? "Mark resolved" : "Resolve…"}
                </Button>
              </div>
            </div>
          </div>
        ) : null}
      </div>
    </Example>
  );
}

export function PartiesOpsSection() {
  return (
    <Section
      id="parties-ops"
      title="Insurance, loyalty, medical records, complaints and supplier prices"
      description="Customer and supplier records beyond contact details. Each states its rule in words: how a scheme bill splits, how points are earned and expire, which lab values are out of range, when a complaint is overdue, which supplier is cheapest and whether that price is still current."
    >
      <SchemeDemo />
      <CustomerRecordsDemo />
      <ComplaintDemo />
      <Example title="Supplier prices: Amoxil 500 mg capsules, 21s" description="Last cost per supplier from goods received. The cheapest current price is marked; prices older than 90 days are stale">
        <SupplierPrices
          product="Amoxil 500 mg capsules, 21s"
          today={TODAY}
          formatDate={fd}
          prices={[
            { supplier: "Harleys Ltd", cost: 290, lastReceived: "2026-10-12", leadDays: 5 },
            { supplier: "Dawa Distributors", cost: 305, lastReceived: "2026-09-28", leadDays: 3 },
            { supplier: "Surgipharm", cost: 270, lastReceived: "2026-05-02", leadDays: 7 },
            { supplier: "Phillips Pharmaceuticals", cost: 312.5, lastReceived: "2026-10-01", leadDays: 4 },
          ]}
        />
      </Example>
    </Section>
  );
}
