"use client";

import { useId, useState } from "react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { formatKES } from "@/lib/format";
import { cn } from "@/lib/utils";
import { RecordStatusBadge } from "./status";

export type ShiftSummaryData = {
  cashier: string;
  branch: string;
  opened: string;
  closed?: string;
  openingFloat: number;
  salesByTender: { method: string; amount: number }[];
  cashRefunds: number;
  /** Counted cash is absent while the shift is still open. */
  countedCash?: number;
};

export function shiftExpectedCash(s: ShiftSummaryData) {
  const cashSales = s.salesByTender.find((t) => t.method === "Cash")?.amount ?? 0;
  return s.openingFloat + cashSales - s.cashRefunds;
}

const row = "flex items-baseline justify-between gap-3 px-3 py-1.5 text-sm";

export function ShiftSummary({ data, loading }: { data: ShiftSummaryData; loading?: boolean }) {
  if (loading) {
    return (
      <div className="max-w-md space-y-2 rounded-lg border border-border bg-card p-3" aria-busy>
        <Skeleton className="h-5 w-40" />
        {Array.from({ length: 6 }, (_, i) => (
          <Skeleton key={i} className="h-4 w-full" />
        ))}
      </div>
    );
  }
  const expected = shiftExpectedCash(data);
  const variance = data.countedCash === undefined ? null : data.countedCash - expected;
  const totalSales = data.salesByTender.reduce((s, t) => s + t.amount, 0);
  const closed = data.closed !== undefined;
  return (
    <div className="max-w-md divide-y divide-border rounded-lg border border-border bg-card">
      <div className="flex items-start justify-between gap-3 p-3">
        <div>
          <h3 className="text-sm font-semibold text-foreground">{closed ? "Z-report" : "Shift in progress"}</h3>
          <p className="text-xs tabular-nums text-muted-foreground">
            {data.cashier}, {data.branch}
          </p>
          <p className="text-xs tabular-nums text-muted-foreground">
            {data.opened}
            {closed ? ` to ${data.closed}` : ""}
          </p>
        </div>
        <RecordStatusBadge domain="shift" status={closed ? "Closed" : "Open"} />
      </div>
      <div className="py-1">
        <div className={row}>
          <span className="text-muted-foreground">Opening float</span>
          <span className="tabular-nums">{formatKES(data.openingFloat)}</span>
        </div>
        {data.salesByTender.map((t) => (
          <div key={t.method} className={row}>
            <span className="text-muted-foreground">Sales, {t.method}</span>
            <span className="tabular-nums">{formatKES(t.amount)}</span>
          </div>
        ))}
        <div className={cn(row, "font-medium")}>
          <span>Total sales</span>
          <span className="tabular-nums">{formatKES(totalSales)}</span>
        </div>
        <div className={row}>
          <span className="text-muted-foreground">Cash refunds</span>
          <span className="tabular-nums">- {formatKES(data.cashRefunds)}</span>
        </div>
      </div>
      <div className="py-1">
        <div className={row}>
          <span className="text-muted-foreground">Expected cash in drawer</span>
          <span className="tabular-nums">{formatKES(expected)}</span>
        </div>
        <div className={row}>
          <span className="text-muted-foreground">Counted cash</span>
          <span className="tabular-nums">{data.countedCash === undefined ? "Not counted" : formatKES(data.countedCash)}</span>
        </div>
      </div>
      <div
        className={cn(
          row,
          "py-2 font-semibold",
          variance === null && "bg-muted/50 text-muted-foreground",
          variance === 0 && "bg-status-success-bg text-status-success-text",
          variance !== null && variance !== 0 && "bg-status-error-bg text-status-error-text",
        )}
      >
        <span>Variance</span>
        <span className="tabular-nums">
          {variance === null ? "Pending count" : variance === 0 ? "Balanced" : `${variance > 0 ? "+" : "-"} ${formatKES(Math.abs(variance))} ${variance > 0 ? "over" : "short"}`}
        </span>
      </div>
    </div>
  );
}

/* --------------------------------------------------------------- Cash count */

const DENOMS = [1000, 500, 200, 100, 50, 40, 20, 10, 5, 1] as const;

export function CashCountForm({
  expected,
  disabled,
  onSubmit,
}: {
  expected: number;
  disabled?: boolean;
  onSubmit?: (counted: number) => void;
}) {
  const uid = useId();
  const [counts, setCounts] = useState<Record<number, string>>({});
  const total = DENOMS.reduce((s, d) => s + d * (Number(counts[d]) || 0), 0);
  const variance = total - expected;
  const touched = Object.values(counts).some((v) => v !== "");
  return (
    <form
      className="max-w-sm rounded-lg border border-border bg-card"
      onSubmit={(e) => {
        e.preventDefault();
        onSubmit?.(total);
      }}
    >
      <div className="border-b border-border px-3 py-2">
        <h3 className="text-sm font-semibold text-foreground">Count the drawer</h3>
        <p className="text-xs text-muted-foreground">Enter how many of each note and coin are in the drawer.</p>
      </div>
      <div className="grid grid-cols-[1fr_5rem_6rem] items-center gap-x-3 gap-y-1.5 p-3 text-sm">
        <span className="text-xs text-muted-foreground">Denomination</span>
        <span className="text-right text-xs text-muted-foreground">Count</span>
        <span className="text-right text-xs text-muted-foreground">Amount</span>
        {DENOMS.map((d) => (
          <div key={d} className="contents">
            <Label htmlFor={`${uid}-${d}`} className="font-normal tabular-nums">
              KES {d.toLocaleString("en-US")}
            </Label>
            <Input
              id={`${uid}-${d}`}
              inputMode="numeric"
              className="h-7 text-right tabular-nums"
              disabled={disabled}
              value={counts[d] ?? ""}
              onChange={(e) => setCounts((c) => ({ ...c, [d]: e.target.value.replace(/\D/g, "") }))}
            />
            <span className="text-right tabular-nums text-muted-foreground">{formatKES(d * (Number(counts[d]) || 0))}</span>
          </div>
        ))}
      </div>
      <div className="space-y-1 border-t border-border px-3 py-2 text-sm">
        <div className="flex justify-between font-medium">
          <span>Counted</span>
          <span className="tabular-nums">{formatKES(total)}</span>
        </div>
        <div className="flex justify-between text-muted-foreground">
          <span>Expected</span>
          <span className="tabular-nums">{formatKES(expected)}</span>
        </div>
        <div className={cn("flex justify-between font-medium", !touched ? "text-muted-foreground" : variance === 0 ? "text-status-success-text" : "text-status-error-text")}>
          <span>Variance</span>
          <span className="tabular-nums">{!touched ? "Not counted" : variance === 0 ? "Balanced" : `${variance > 0 ? "+" : "-"} ${formatKES(Math.abs(variance))}`}</span>
        </div>
      </div>
      <div className="flex justify-end border-t border-border p-2">
        <Button type="submit" size="sm" disabled={disabled || !touched}>
          Close shift
        </Button>
      </div>
    </form>
  );
}
