"use client";
import { useState } from "react";
import {
  Panel,
  PreviewNotice,
  StatusBadge,
  DetailList,
} from "@/components/shared/page";
import { DataTable } from "@/components/shared/data-table";
import { Field } from "@/components/shared/field";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { currency } from "@/lib/format";
import { downloadCsv } from "@/lib/export";
import {
  generateSettlement,
  transitionSettlement,
  type BusinessContract,
  type Settlement,
} from "./model";
export function Settlements({
  contract,
  onChange,
}: {
  contract: BusinessContract;
  onChange: (rows: Settlement[]) => void;
}) {
  const [open, setOpen] = useState(false),
    [preview, setPreview] = useState<Settlement | null>(null),
    [detail, setDetail] = useState<Settlement | null>(null),
    [error, setError] = useState(""),
    [transition, setTransition] = useState<{
      row: Settlement;
      next: Settlement["status"];
    } | null>(null);
  return (
    <div className="space-y-5">
      <PreviewNotice>
        Settlement generation calculates a fixture distribution. Locking,
        rollback, and paid states affect this local preview only.
      </PreviewNotice>
      <DataTable
        title="Settlements"
        rows={contract.settlements}
        columns={[
          { key: "start", label: "Period Start" },
          { key: "end", label: "Period End" },
          {
            key: "gross",
            label: "Gross Revenue",
            render: (row) => currency(row.gross),
          },
          {
            key: "deductions",
            label: "Deductions",
            render: (row) => currency(row.deductions),
          },
          {
            key: "net",
            label: "Net Revenue",
            render: (row) => currency(row.net),
          },
          {
            key: "status",
            label: "Status",
            render: (row) => <StatusBadge>{row.status}</StatusBadge>,
          },
        ]}
        filters={[
          {
            key: "status",
            label: "Status",
            options: ["DRAFT", "LOCKED", "PAID"],
          },
        ]}
        onCreate={() => {
          setOpen(true);
          setPreview(null);
          setError("");
        }}
        createLabel="Generate Settlement"
        actions={(row) => (
          <>
            <Button size="sm" variant="outline" onClick={() => setDetail(row)}>
              View
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() =>
                downloadCsv(
                  `${contract.code}-${row.start}`,
                  row.distribution.map((item) => ({
                    Participant: item.participant,
                    "Amount (IDR)": item.amount,
                    Status: row.status,
                  })),
                )
              }
            >
              CSV
            </Button>
            {row.status === "DRAFT" && (
              <Button
                size="sm"
                variant="outline"
                onClick={() => setTransition({ row, next: "LOCKED" })}
              >
                Lock
              </Button>
            )}
            {row.status === "LOCKED" && (
              <>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => setTransition({ row, next: "DRAFT" })}
                >
                  Rollback
                </Button>
                <Button
                  size="sm"
                  onClick={() => setTransition({ row, next: "PAID" })}
                >
                  Mark Paid
                </Button>
              </>
            )}
          </>
        )}
      />
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="sm:max-w-xl">
          <DialogHeader>
            <DialogTitle>Generate Settlement</DialogTitle>
            <DialogDescription>
              Estimate monthly terms that cover the full selected period.
              Recurring payment frequency, due dates and partial-period
              proration require backend rules. No payout occurs.
            </DialogDescription>
          </DialogHeader>
          <form
            onSubmit={(event) => {
              event.preventDefault();
              const data = new FormData(event.currentTarget);
              try {
                setPreview(
                  generateSettlement(
                    contract,
                    String(data.get("start")),
                    String(data.get("end")),
                    Number(data.get("gross")),
                    crypto.randomUUID(),
                  ),
                );
                setError("");
              } catch (cause) {
                setError(
                  cause instanceof Error
                    ? cause.message
                    : "Unable to generate settlement.",
                );
              }
            }}
          >
            <div className="grid gap-4 sm:grid-cols-2">
              <Field
                label="Period Start"
                name="start"
                type="date"
                required
                min={contract.start}
                max={contract.end || undefined}
                defaultValue="2026-10-01"
              />
              <Field
                label="Period End"
                name="end"
                type="date"
                required
                min={contract.start}
                max={contract.end || undefined}
                defaultValue="2026-10-15"
              />
              <Field
                label="Gross Revenue (IDR)"
                name="gross"
                type="number"
                min={0}
                step="0.01"
                required
                defaultValue={30000000}
              />
            </div>
            {error && (
              <p role="alert" className="mt-3 text-sm text-destructive">
                {error}
              </p>
            )}
            <Button className="mt-4" variant="outline">
              Calculate Preview
            </Button>
          </form>
          {preview && (
            <div className="space-y-3 border-t pt-4">
              <p className="text-sm">
                Net revenue: <strong>{currency(preview.net)}</strong> ·
                Deductions: {currency(preview.deductions)}
              </p>
              {preview.distribution.map((item, index) => (
                <div className="flex justify-between text-sm" key={index}>
                  <span>{item.participant}</span>
                  <span>{currency(item.amount)}</span>
                </div>
              ))}
              {!preview.distribution.length && (
                <p className="text-sm text-muted-foreground">
                  No active participant terms in this period.
                </p>
              )}
              <DialogFooter>
                <Button variant="outline" onClick={() => setOpen(false)}>
                  Cancel
                </Button>
                <Button
                  onClick={() => {
                    onChange([...contract.settlements, preview]);
                    setOpen(false);
                  }}
                >
                  Save Draft Preview
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>
      <Dialog
        open={!!detail}
        onOpenChange={(open) => {
          if (!open) setDetail(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Settlement Distribution</DialogTitle>
            <DialogDescription>
              {detail?.start} → {detail?.end} · {detail?.status}
            </DialogDescription>
          </DialogHeader>
          {detail && (
            <>
              <DetailList
                items={{
                  "Gross Revenue": currency(detail.gross),
                  Deductions: currency(detail.deductions),
                  "Net Revenue": currency(detail.net),
                }}
              />
              <Panel title="Participant Distribution">
                <div className="space-y-3 p-5">
                  {detail.distribution.map((item, index) => (
                    <div
                      key={index}
                      className="flex justify-between gap-4 text-sm"
                    >
                      <span>{item.participant}</span>
                      <strong>{currency(item.amount)}</strong>
                    </div>
                  ))}
                </div>
              </Panel>
            </>
          )}
        </DialogContent>
      </Dialog>
      <Dialog
        open={!!transition}
        onOpenChange={(open) => {
          if (!open) setTransition(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              {transition?.next === "LOCKED"
                ? "Lock Settlement"
                : transition?.next === "PAID"
                  ? "Mark Settlement Paid"
                  : "Rollback Settlement"}
            </DialogTitle>
            <DialogDescription>
              Change {transition?.row.start} – {transition?.row.end} from{" "}
              {transition?.row.status} to {transition?.next} in this local
              preview?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setTransition(null)}>
              Cancel
            </Button>
            <Button
              onClick={() => {
                if (transition) {
                  onChange(
                    contract.settlements.map((row) =>
                      row.id === transition.row.id
                        ? transitionSettlement(row, transition.next)
                        : row,
                    ),
                  );
                  setTransition(null);
                }
              }}
            >
              Confirm Preview
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
