"use client";

import * as React from "react";

import { Example } from "@/components/design-system/example";
import { Section } from "@/components/design-system/section";
import { CategoryMarginChart, StaffRankChart } from "@/components/medora/report-charts";
import { DashboardFilters, FinancialOverview, GeneralReport, StaffPLTable, StockingTable, type DashFilter } from "@/components/medora/reports-more";
import { ReportFilterBar } from "@/components/medora/records/reports";
import { toast } from "@/components/ui/toast";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";

const STAFF = [
  { staff: "Kevin Mutua", sales: 412300, returns: 6200, cost: 296800 },
  { staff: "Faith Njeri", sales: 268900, returns: 11100, cost: 188400 },
  { staff: "Grace Wanjiru", sales: 530100, returns: 0, cost: 371000 },
];

const describe = (f: DashFilter) => `${f.preset === "today" ? "today, 20 Oct 2026" : f.preset === "7d" ? "the last 7 days, 14–20 Oct 2026" : f.preset === "mtd" ? "this month, 1–20 Oct 2026" : `${f.from || "?"} to ${f.to || "?"}`} · ${f.branch || "all branches"}`;

function FiltersDemo() {
  const [applied, setApplied] = React.useState<DashFilter>({ preset: "mtd", from: "", to: "", branch: "" });
  return (
    <Example title="Dashboard filters" description="Change the period and branch, then Apply once: every panel reloads together. Apply stays off until something changed">
      <DashboardFilters
        applied={applied}
        branches={["Westlands Main", "Kilimani", "Nyali", "Milimani"]}
        describe={describe}
        onApply={(f) => {
          setApplied(f);
          toast.add({ title: "Dashboard updated", description: describe(f) });
        }}
      />
    </Example>
  );
}

function ExecutiveDemo() {
  const [tab, setTab] = React.useState<"category" | "staff" | "stocking">("category");
  return (
    <Example title="Executive pack" description="For the owner: P&L by category and by staff member, and whether buying kept pace with selling, with branch and date filters and export (AC-19)" bare>
      <div className="border-b border-border px-4 py-3">
        <ReportFilterBar
          today="2026-10-20"
          branches={[
            { id: 1, name: "Westlands Main" },
            { id: 2, name: "Kilimani" },
            { id: 3, name: "Nyali" },
            { id: 4, name: "Milimani" },
          ]}
          onExport={(k) => toast.add({ title: `Exporting the executive pack as ${k === "excel" ? "Excel" : k.toUpperCase()}`, description: "Exactly what's on screen: the tab, period and branch chosen." })}
        />
      </div>
      <div className="border-b border-border px-4 py-3">
        <ToggleGroup variant="outline" size="sm" spacing={0} aria-label="Executive report" value={[tab]} onValueChange={(v: string[]) => v[0] && setTab(v[0] as typeof tab)}>
          <ToggleGroupItem value="category">By category</ToggleGroupItem>
          <ToggleGroupItem value="staff">By staff</ToggleGroupItem>
          <ToggleGroupItem value="stocking">Stocking</ToggleGroupItem>
        </ToggleGroup>
      </div>
      <div className="overflow-x-auto p-4">
        {tab === "category" ? (
          <CategoryMarginChart
            rows={[
              { category: "Antibiotics", revenue: 312400, cost: 228100 },
              { category: "Analgesics", revenue: 198300, cost: 112700 },
              { category: "Antidiabetics", revenue: 176500, cost: 141900 },
              { category: "Dermatology", revenue: 121200, cost: 88400 },
              { category: "Vitamins", revenue: 96400, cost: 61200 },
              { category: "Consumables", revenue: 54800, cost: 47900 },
            ]}
          />
        ) : tab === "staff" ? (
          <div className="space-y-6">
            <StaffRankChart rows={STAFF} />
            <StaffPLTable rows={STAFF} />
          </div>
        ) : (
          <StockingTable
            rows={[
              { item: "Panadol 500 mg, strips", bought: 600, sold: 540, unit: "strips" },
              { item: "Nivea Soft cream 200 ml", bought: 48, sold: 12, unit: "tubes" },
              { item: "Amoxil 500 mg, 21s", bought: 60, sold: 96, unit: "packs" },
              { item: "Calamine lotion 100 ml", bought: 24, sold: 0, unit: "bottles" },
            ]}
          />
        )}
      </div>
    </Example>
  );
}

export function ReportsMoreSection() {
  return (
    <Section id="reports-more" title="Dashboard filters, financial overview, general report and executive pack" description="Owner and manager reporting. Each labels its basis in words: which period and branch a figure is for, what's included, and when a total isn't profit.">
      <FiltersDemo />
      <div className="grid gap-4 lg:grid-cols-2">
        <Example title="Financial overview" description="August to October 2026, all branches. October is to the 20th, so it is not a full month">
          <FinancialOverview
            months={[
              { label: "Aug", sales: 1693800, purchases: 1210400, expenses: 498600 },
              { label: "Sep", sales: 1742300, purchases: 1388900, expenses: 512300 },
              { label: "Oct (to 20th)", sales: 1284600, purchases: 842100, expenses: 341000 },
            ]}
          />
        </Example>
        <Example title="General report" description="Sales by tender less credit notes, then sales less purchases, which is not profit">
          <GeneralReport
            invoices={96420}
            byTender={[
              { tender: "M-Pesa", amount: 741200 },
              { tender: "Cash", amount: 398500 },
              { tender: "Card", amount: 96400 },
              { tender: "Credit", amount: 48500 },
            ]}
            creditNotes={18240}
            purchases={842100}
            onOpenPL={() => toast.add({ title: "Opens Accounts, Profit & loss" })}
          />
        </Example>
      </div>
      <ExecutiveDemo />
    </Section>
  );
}
