"use client";

import { Calendar } from "lucide-react";
import { BrapiEntityPage } from "@/components/brapi/BrapiEntityPage";
import { createSeason, deleteSeason, listSeasons, updateSeason } from "@/services/dictionaryService";

const loadSeasonRows = async () => listSeasons() as unknown as Record<string, unknown>[];

const normalizeSeasonPayload = (payload: Record<string, unknown>) => {
  const seasonName = String(payload.seasonName ?? "").trim();
  const yearValue = String(payload.year ?? "").trim();
  return {
    seasonName: seasonName || null,
    year: yearValue ? Number(yearValue) : null,
  };
};

const createSeasonRow = async (payload: Record<string, unknown>) =>
  createSeason(normalizeSeasonPayload(payload)) as unknown as Record<string, unknown>;

const updateSeasonRow = async (id: string, payload: Record<string, unknown>) =>
  updateSeason(id, normalizeSeasonPayload(payload)) as unknown as Record<string, unknown>;

export default function Page() {
  return (
    <BrapiEntityPage
      icon={Calendar}
      iconBg="bg-gradient-to-br from-sky-500 to-blue-600"
      title="Season 季节"
      description="维护 BrAPI 标准 season 表，用于 Study 的年份、季节和试验周期关联"
      addLabel="新增季节"
      columns={[
        { key: "seasonDbId", label: "Season DbId" },
        { key: "seasonName", label: "季节名称" },
        { key: "year", label: "年份" },
      ]}
      fields={[
        { key: "seasonName", label: "季节名称 (Season Name)", type: "text", required: true, placeholder: "Spring / Summer / Rainy / 2026 Spring" },
        { key: "year", label: "年份", type: "year", required: true, placeholder: "请选择年份" },
      ]}
      data={[]}
      stats={[{ label: "/brapi/v2/seasons", value: "BrAPI", className: "bg-sky-50 text-sky-700 dark:bg-sky-400/10 dark:text-sky-200" }]}
      loadData={loadSeasonRows}
      createRecord={createSeasonRow}
      updateRecord={updateSeasonRow}
      deleteRecord={deleteSeason}
    />
  );
}
