"use client";
import { SearchablePicker } from "./searchable-picker";
import { useRef, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Field, SelectField, TextareaField } from "@/components/shared/field";
import {
  isRecord,
  parseFinancialInput,
  numeric,
  isId,
  text,
  type FinancialRecord,
  type FinancialOptions,
} from "./contract";
import { date, money } from "./display";
export type FinancialDialog = {
  action: "create-settlement" | "update-settlement";
  row?: FinancialRecord;
};
type PayoutCandidate = {
  id: string;
  revenueShareId: string;
  amount: number;
  currency: string;
  billingPeriod: string;
  chargepointName: string;
};
function payoutCandidates(
  rows: FinancialRecord[],
  recipientId: string,
): PayoutCandidate[] {
  const candidates = new Map<string, PayoutCandidate>();
  if (!recipientId) return [];
  for (const row of rows) {
    if (!Array.isArray(row.items)) continue;
    for (const item of row.items) {
      if (!isRecord(item) || item.recipient_type !== "investor" || !isId(row.id))
        continue;
      const itemId = isId(item.id) ? item.id : item.revenue_share_item_id;
      const itemRecipient =
        text(item, "recipient_id") || text(item, "investor_user_id");
      if (!isId(itemId) || itemRecipient !== recipientId) continue;
      const amount = numeric(item.amount);
      const currency = text(item, "currency") || row.currency;
      const status = text(item, "status").toLowerCase();
      if (
        amount === null ||
        amount <= 0 ||
        !/^[A-Z]{3}$/.test(currency) ||
        status === "paid" ||
        status === "settled" ||
        !!text(item, "payout_settlement_id") ||
        !!text(item, "settlement_id")
      )
        continue;
      candidates.set(itemId, {
        id: itemId,
        revenueShareId: row.id,
        amount,
        currency,
        billingPeriod: text(row, "billing_period"),
        chargepointName: text(row, "charge_point_name"),
      });
    }
  }
  return Array.from(candidates.values());
}
function currentSettlementMonth() {
  const parts = new Intl.DateTimeFormat("en", {
    timeZone: "Asia/Jakarta",
    year: "numeric",
    month: "2-digit",
  }).formatToParts(new Date());
  const year = parts.find((part) => part.type === "year")?.value ?? "";
  const month = parts.find((part) => part.type === "month")?.value ?? "";
  return `${year}-${month}`;
}
export async function financialFetch(
  path: string,
  method = "GET",
  body?: unknown,
): Promise<unknown> {
  const response = await fetch(`/api/financial/${path}`, {
    method,
    cache: "no-store",
    ...(body
      ? {
          headers: { "content-type": "application/json" },
          body: JSON.stringify(body),
        }
      : {}),
  });
  const data: unknown = response.status === 204 ? null : await response.json();
  if (!response.ok || (isRecord(data) && data.ok === false))
    throw new Error(
      isRecord(data) && typeof data.error === "string"
        ? data.error
        : "The financial request failed. Refresh the records before trying again.",
    );
  return data;
}
export function FinancialFormDialog({
  dialog,
  close,
  investors,
  revenueShares,
  revenueError,
}: {
  investors: FinancialOptions;
  revenueShares: FinancialRecord[];
  revenueError?: string;
  dialog: FinancialDialog;
  close: () => void;
}) {
  const { action, row } = dialog;
  const router = useRouter();
  const [busy, setBusy] = useState(false),
    [error, setError] = useState("");
  const errorRef = useRef<HTMLParagraphElement>(null),
    submitting = useRef(false);
  const creatingSettlement = action === "create-settlement";
  const [recipientId, setRecipientId] = useState("");
  const [settlementCurrency, setSettlementCurrency] = useState("");
  const [selectedShareIds, setSelectedShareIds] = useState<Set<string>>(
    new Set(),
  );
  const [settlementMonth, setSettlementMonth] = useState(
    currentSettlementMonth,
  );
  const eligibleShares = creatingSettlement
    ? payoutCandidates(revenueShares, recipientId)
    : [];
  const settlementCurrencies = Array.from(
    new Set(eligibleShares.map((share) => share.currency)),
  ).sort();
  const visibleShares = eligibleShares.filter(
    (share) => share.currency === settlementCurrency,
  );
  const selectedTotal = visibleShares
    .filter((share) => selectedShareIds.has(share.id))
    .reduce((total, share) => total + share.amount, 0);
  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (submitting.current) return;
    setError("");
    const data = new FormData(event.currentTarget);
    const input: Record<string, unknown> = Object.fromEntries(data);
    if (creatingSettlement) {
      const month = data.get("settlement_month");
      input.settlement_period =
        typeof month === "string" && /^\d{4}-\d{2}$/.test(month)
          ? `${month}-01T00:00:00+07:00`
          : "";
      input.period_type = "monthly";
      input.recipient_type = "investor";
      const selectedIds = new Set(
        data.getAll("selected_share_item_ids").filter(
          (value): value is string => typeof value === "string",
        ),
      );
      input.items = eligibleShares
        .filter(
          (share) =>
            share.currency === data.get("currency") &&
            selectedIds.has(share.id),
        )
        .map((share) => ({
          revenue_share_item_id: share.id,
          revenue_share_id: share.revenueShareId,
          amount: share.amount,
          currency: share.currency,
        }));
      input.meta_data = {};
    }
    const paidAt = data.get("paid_at");
    if (typeof paidAt === "string" && paidAt) input.paid_at = `${paidAt}:00+07:00`;
    else delete input.paid_at;
    const payload = parseFinancialInput(action, input);
    if (!payload) {
      setError(
        creatingSettlement
          ? "Choose an investor, a valid settlement month and currency, and at least one eligible revenue share."
          : "Check the settlement fields. A paid settlement requires a payment reference and paid date.",
      );
      requestAnimationFrame(() => errorRef.current?.focus());
      return;
    }
    submitting.current = true;
    setBusy(true);
    try {
      await financialFetch(
        creatingSettlement ? "payout-settlements" : `payout-settlements/${row?.id}/status`,
        creatingSettlement ? "POST" : "PATCH",
        payload,
      );
      router.refresh();
      close();
    } catch (err) {
      setError(
        err instanceof Error
          ? err.message
          : "Unable to save. Reload the records to check their current state before retrying.",
      );
      requestAnimationFrame(() => errorRef.current?.focus());
    } finally {
      submitting.current = false;
      setBusy(false);
    }
  }
  function localDate(value: unknown) {
    if (typeof value !== "string" || !Number.isFinite(Date.parse(value)))
      return "";
    return new Date(Date.parse(value) + 7 * 3600000).toISOString().slice(0, 16);
  }
  return (
    <Dialog
      open
      onOpenChange={(open) => {
        if (!open && !busy) close();
      }}
    >
      <DialogContent
        className="max-h-[90dvh] overflow-y-auto sm:max-w-2xl"
        onInteractOutside={(event) => {
          if (busy) event.preventDefault();
        }}
      >
        <DialogHeader>
          <DialogTitle>{creatingSettlement ? "Create payout settlement" : "Update payout settlement"}</DialogTitle>
          <DialogDescription>
            {creatingSettlement
              ? "Select the revenue shares to include in this investor payout. This records a settlement without transferring money."
              : "Record the settlement status and transfer reference. This does not initiate a bank transfer."}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={submit} className="space-y-5">
          {error && (
            <p
              ref={errorRef}
              tabIndex={-1}
              role="alert"
              className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive"
            >
              {error}
            </p>
          )}
          <fieldset disabled={busy} className="grid gap-4 sm:grid-cols-2">
            {creatingSettlement && (
              <>
                <SearchablePicker
                  name="recipient_id"
                  label="Investor"
                  choices={investors}
                  disabled={busy}
                  includeInactive
                  retry={() => router.refresh()}
                  onValueChange={(value) => {
                    setRecipientId(value);
                    setSelectedShareIds(new Set());
                    const currencies = Array.from(
                      new Set(
                        payoutCandidates(revenueShares, value).map(
                          (share) => share.currency,
                        ),
                      ),
                    );
                    setSettlementCurrency(
                      currencies.length === 1 ? currencies[0] : "",
                    );
                  }}
                />
                <SelectField
                  name="currency"
                  label="Currency"
                  required
                  value={settlementCurrency}
                  onChange={(event) => {
                    setSettlementCurrency(event.target.value);
                    setSelectedShareIds(new Set());
                  }}
                  options={[
                    { value: "", label: "Select currency" },
                    ...settlementCurrencies.map((currency) => ({
                      value: currency,
                      label: currency,
                    })),
                  ]}
                />
                <Field
                  name="settlement_month"
                  label="Settlement month (Jakarta)"
                  type="month"
                  required
                  value={settlementMonth}
                  onChange={(event) => setSettlementMonth(event.target.value)}
                />
                <div className="space-y-2 sm:col-span-2">
                  <p className="field-label text-sm">
                    Revenue share items *
                  </p>
                  {revenueError ? (
                    <p role="alert" className="text-sm text-destructive">
                      {revenueError}
                    </p>
                  ) : !recipientId ? (
                    <p className="text-sm text-muted-foreground">
                      Choose an investor to see eligible revenue shares.
                    </p>
                  ) : visibleShares.length === 0 ? (
                    <p className="text-sm text-muted-foreground">
                      No eligible revenue share items for this investor and
                      currency were returned.
                    </p>
                  ) : (
                    <div className="max-h-56 space-y-2 overflow-y-auto rounded-lg border p-3">
                      {visibleShares.map((share) => (
                        <label
                          key={share.id}
                          className="flex cursor-pointer items-start gap-3 rounded-md p-2 hover:bg-muted/40"
                        >
                          <input
                            type="checkbox"
                            name="selected_share_item_ids"
                            value={share.id}
                            checked={selectedShareIds.has(share.id)}
                            onChange={(event) => {
                              setSelectedShareIds((current) => {
                                const next = new Set(current);
                                if (event.target.checked) next.add(share.id);
                                else next.delete(share.id);
                                return next;
                              });
                            }}
                            className="mt-1 size-4 accent-primary"
                          />
                          <span className="min-w-0 flex-1">
                            <span className="block font-medium">
                              {share.chargepointName || "Revenue share"} ·{" "}
                              {date(share.billingPeriod)}
                            </span>
                            <span className="block text-xs text-muted-foreground">
                              {money(share.amount, share.currency)}
                            </span>
                          </span>
                        </label>
                      ))}
                    </div>
                  )}
                  <p className="text-xs text-muted-foreground">
                    Selected total: {" "}
                    {settlementCurrency
                      ? money(selectedTotal, settlementCurrency)
                      : "—"}
                  </p>
                </div>
              </>
            )}
            {action === "update-settlement" && (
              <>
                <Field
                  name="status"
                  label="Settlement status"
                  required
                  defaultValue={row ? text(row, "status") : ""}
                  placeholder="e.g. paid"
                  pattern="[a-z_]+"
                />
                <Field
                  name="payment_reference"
                  label="Payment reference"
                  maxLength={255}
                  defaultValue={row ? text(row, "payment_reference") : ""}
                />
                <Field
                  name="paid_at"
                  label="Paid at (Jakarta)"
                  type="datetime-local"
                  defaultValue={localDate(row?.paid_at)}
                />
              </>
            )}
            <div className="sm:col-span-2">
              <TextareaField
                name="notes"
                label="Notes"
                maxLength={2000}
                defaultValue={
                  row && isRecord(row.meta_data)
                    ? text(row.meta_data, "notes")
                    : row
                      ? text(row, "notes")
                      : ""
                }
              />
            </div>
          </fieldset>
          <div className="flex justify-end gap-2">
            <Button
              type="button"
              variant="outline"
              disabled={busy}
              onClick={close}
            >
              Cancel
            </Button>
            <Button
              disabled={
                busy ||
                (creatingSettlement &&
                  (!!investors.error ||
                    investors.options.length === 0 ||
                    !!revenueError ||
                    eligibleShares.length === 0 ||
                    !settlementCurrency ||
                    selectedShareIds.size === 0))
              }
              type="submit"
            >
              {busy
                ? "Saving…"
                : creatingSettlement
                  ? "Create payout settlement"
                  : "Save changes"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
