"use client";

import Link from "next/link";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import {
  postSettlementPeriodClose,
  type SettlementPeriodCloseResult,
  type SettlementPeriodRow,
} from "@/api/admin-agent-settlement";
import { AdminStatusBadge } from "@/components/admin/admin-status-badge";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { formatSettlementPeriodSpan } from "@/lib/agent-settlement-period-range";
import { formatDashboardMoneyMinor } from "@/modules/dashboard/use-dashboard-analytics";
import {
  settlementCenterListHref,
  settlementPeriodViewHref,
  type SettlementBillScopeFilter,
} from "@/modules/settlement/settlement-center-nav";
import { settlementPeriodStatusLabel } from "@/modules/settlement/settlement-status-label";
import { LotteryApiBizError } from "@/types/api/errors";
import { cn } from "@/lib/utils";

type SettlementPeriodHeaderProps = {
  period: SettlementPeriodRow;
  adminSiteId: number;
  currencyCode: string;
  billScope: SettlementBillScopeFilter;
  canManage: boolean;
  onPeriodClosed?: (result: SettlementPeriodCloseResult) => void;
  onReloadPeriods?: () => Promise<unknown>;
};

function scopeChipClass(active: boolean): string {
  return cn(
    "inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",
    active
      ? "border-primary/40 bg-primary/10 text-primary"
      : "border-border/70 bg-muted/40 text-muted-foreground hover:bg-muted/70 hover:text-foreground",
  );
}

export function SettlementPeriodHeader({
  period,
  adminSiteId,
  currencyCode,
  billScope,
  canManage,
  onPeriodClosed,
  onReloadPeriods,
}: SettlementPeriodHeaderProps): React.ReactElement {
  const { t } = useTranslation(["settlementCenter", "agents", "common"]);
  const [closeDialogOpen, setCloseDialogOpen] = useState(false);
  const [busy, setBusy] = useState(false);

  const pendingConfirm = period.summary?.pending_confirm ?? 0;
  const awaitingPayment = period.summary?.awaiting_payment ?? 0;
  const totalUnpaid = period.summary?.total_unpaid ?? 0;
  const shareCount = period.pipeline?.share_ledger_count ?? 0;
  const unsettledCount = period.pipeline?.unsettled_ticket_count ?? 0;
  const isOpen = period.status === "open";

  const scopeChips: { key: SettlementBillScopeFilter; label: string; count?: number }[] = [
    {
      key: "all",
      label: t("billsPanel.filterAll", { defaultValue: "全部" }),
    },
    {
      key: "pending_confirm",
      label: t("billsPanel.category.pendingConfirm", { defaultValue: "待确认" }),
      count: pendingConfirm,
    },
    {
      key: "awaiting_payment",
      label: t("billsPanel.category.awaitingPayment", { defaultValue: "待收付" }),
      count: awaitingPayment,
    },
  ];

  async function confirmClose(): Promise<void> {
    setBusy(true);
    try {
      const result = await postSettlementPeriodClose(period.id);
      await onReloadPeriods?.();
      setCloseDialogOpen(false);
      onPeriodClosed?.(result);
      const n = result.unsettled_ticket_count ?? 0;
      if (n > 0) {
        toast.warning(
          t("toast.periodClosedUnsettled", {
            defaultValue: "已关账，仍有 {{count}} 笔注单未结算。",
            count: n,
          }),
        );
      } else {
        toast.success(t("agents:settlementPeriods.closed", { defaultValue: "账期已关账，账单已生成" }));
      }
    } catch (err: unknown) {
      toast.error(
        err instanceof LotteryApiBizError
          ? err.message
          : t("agents:settlementPeriods.closeFailed", { defaultValue: "关账失败" }),
      );
    } finally {
      setBusy(false);
    }
  }

  return (
    <>
      <div className="flex flex-col gap-3">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div className="flex min-w-0 flex-col gap-2">
            <Link
              href={settlementCenterListHref(adminSiteId)}
              className="w-fit text-sm text-muted-foreground hover:text-foreground hover:underline"
            >
              ← {t("periodDetail.back", { defaultValue: "返回账期列表" })}
            </Link>
            <div className="flex flex-wrap items-center gap-2">
              <h2 className="text-base font-semibold tracking-tight">
                {formatSettlementPeriodSpan(period.period_start, period.period_end)}
              </h2>
              <AdminStatusBadge status={period.status}>
                {settlementPeriodStatusLabel(period.status, t)}
              </AdminStatusBadge>
            </div>
          </div>
          {canManage && isOpen ? (
            <Button type="button" size="sm" disabled={busy} onClick={() => setCloseDialogOpen(true)}>
              {t("periodTable.close", { defaultValue: "关账" })}
            </Button>
          ) : null}
        </div>

        {!isOpen ? (
          <div className="flex flex-wrap items-center gap-2">
            {scopeChips.map((chip) => {
              const active = billScope === chip.key;
              const href = settlementPeriodViewHref(period.id, "bills", adminSiteId, chip.key);

              return (
                <Link key={chip.key} href={href} className={scopeChipClass(active)}>
                  {chip.label}
                  {chip.count != null && chip.count > 0 ? ` ${chip.count}` : null}
                </Link>
              );
            })}
            {totalUnpaid > 0 ? (
              <span className="text-xs text-muted-foreground">
                {t("overview.totalUnpaid", { defaultValue: "未结合计" })}{" "}
                <span className="font-medium tabular-nums text-foreground">
                  {formatDashboardMoneyMinor(totalUnpaid, currencyCode)}
                </span>
              </span>
            ) : null}
          </div>
        ) : (
          <p className="text-xs text-muted-foreground">
            {t("overview.pipelineHint", {
              defaultValue: "账单须关账后生成；下方为账期内实时流水笔数。",
            })}
            {shareCount > 0
              ? ` · ${t("period.pipelineShare", { defaultValue: "流水 {{count}} 笔", count: shareCount })}`
              : null}
          </p>
        )}
      </div>

      <Dialog open={closeDialogOpen} onOpenChange={setCloseDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("period.closeDialogTitle", { defaultValue: "确认关账" })}</DialogTitle>
            <DialogDescription>
              {t("period.closeDialogDesc", {
                defaultValue: "将汇总 {{range}} 内的流水并生成账单。",
                range: formatSettlementPeriodSpan(period.period_start, period.period_end),
              })}
            </DialogDescription>
          </DialogHeader>
          <ul className="list-inside list-disc space-y-1 text-sm text-muted-foreground">
            <li>
              {shareCount > 0
                ? t("period.closeDialogShare", {
                    defaultValue: "流水 {{count}} 笔",
                    count: shareCount,
                  })
                : t("period.closeDialogEmpty", {
                    defaultValue: "本期暂无占成流水，关账后不会生成账单。",
                  })}
            </li>
            {unsettledCount > 0 ? (
              <li className="text-amber-800">
                {t("period.closeDialogUnsettled", {
                  defaultValue: "仍有 {{count}} 笔注单未结算",
                  count: unsettledCount,
                })}
              </li>
            ) : null}
          </ul>
          <DialogFooter>
            <Button type="button" variant="outline" disabled={busy} onClick={() => setCloseDialogOpen(false)}>
              {t("common:cancel", { defaultValue: "取消" })}
            </Button>
            <Button type="button" disabled={busy} onClick={() => void confirmClose()}>
              {t("period.closeDialogConfirm", { defaultValue: "确认关账" })}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}