"use client";

import { useTranslation } from "react-i18next";

import { formatSettlementPeriodSpan } from "@/lib/agent-settlement-period-range";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import type { SettlementPeriodRow } from "@/api/admin-agent-settlement";

export type AgentSettlementPeriodFilter = number | "all";

type AgentSettlementPeriodSelectProps = {
  periods: SettlementPeriodRow[];
  value: AgentSettlementPeriodFilter;
  onChange: (value: AgentSettlementPeriodFilter) => void;
  className?: string;
};

export function AgentSettlementPeriodSelect({
  periods,
  value,
  onChange,
  className,
}: AgentSettlementPeriodSelectProps): React.ReactElement {
  const { t } = useTranslation(["agents", "settlementCenter"]);

  const sorted = [...periods].sort((a, b) => b.id - a.id);

  const periodLabel = (filter: AgentSettlementPeriodFilter): string => {
    if (filter === "all") {
      return t("settlementCenter:filters.allPeriods", {
        defaultValue: t("agents:settlementBills.allPeriods", { defaultValue: "全部账期" }),
      });
    }

    const row = periods.find((p) => p.id === filter);
    if (!row) {
      return t("agents:settlementBills.periodPlaceholder", { defaultValue: "选择账期" });
    }

    return `${formatSettlementPeriodSpan(row.period_start, row.period_end)} · ${periodStatusLabel(row.status, t)}`;
  };

  return (
    <Select
      modal={false}
      value={value === "all" ? "all" : String(value)}
      onValueChange={(next) => {
        onChange(next === "all" ? "all" : Number(next));
      }}
    >
      <SelectTrigger className={className ?? "h-9 w-full max-w-md"}>
        <SelectValue placeholder={t("agents:settlementBills.periodPlaceholder", { defaultValue: "选择账期" })}>
          {() => periodLabel(value)}
        </SelectValue>
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="all">
          {t("settlementCenter:filters.allPeriods", {
            defaultValue: t("agents:settlementBills.allPeriods", { defaultValue: "全部账期" }),
          })}
        </SelectItem>
        {sorted.map((row) => (
          <SelectItem key={row.id} value={String(row.id)}>
            {formatSettlementPeriodSpan(row.period_start, row.period_end)}
            {" · "}
            {periodStatusLabel(row.status, t)}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

function periodStatusLabel(
  status: string,
  t: (key: string, opts?: { defaultValue?: string }) => string,
): string {
  if (status === "open") {
    return t("agents:settlementPeriods.statusOpen", { defaultValue: "进行中" });
  }
  if (status === "closed") {
    return t("agents:settlementPeriods.statusClosed", { defaultValue: "已关账" });
  }
  if (status === "completed") {
    return t("settlementCenter:filters.statusCompleted", { defaultValue: "已结清" });
  }

  return status;
}
