"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { Network, RotateCcw, Search } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  createCrossingProjectRow,
  fetchCrossingProjectDetail,
  fetchCrossingProjectRows,
  normalizeCrossingProjectForm,
  updateCrossingProjectRow,
} from "../api";
import { useCrossPedigree } from "../CrossPedigreeContext";
import { NONE_SELECT_VALUE, type CrossingProjectQuery } from "../types";

const emptyQuery = (): CrossingProjectQuery => ({
  keyword: "",
  program_id: NONE_SELECT_VALUE,
});

export function CrossingProjectTab() {
  const { snapshot, refresh } = useCrossPedigree();
  const programOptions = snapshot?.programs ?? [];
  const [draftQuery, setDraftQuery] = useState<CrossingProjectQuery>(emptyQuery);
  const [appliedQuery, setAppliedQuery] = useState<CrossingProjectQuery>(emptyQuery);

  const loadRows = useCallback(async () => {
    await refresh(false);
    const rows = await fetchCrossingProjectRows(appliedQuery);
    return rows as unknown as Record<string, unknown>[];
  }, [appliedQuery, refresh]);

  const fetchRecord = useCallback(async (id: string) => {
    const detail = await fetchCrossingProjectDetail(id);
    return normalizeCrossingProjectForm(detail);
  }, []);

  const fields = useMemo<BrapiFormField[]>(() => [
    {
      key: "name",
      label: "杂交项目名称",
      type: "text",
      required: true,
      placeholder: "如 2026 抗倒伏杂交项目",
    },
    {
      key: "program_id",
      label: "所属 Program",
      type: "select",
      required: true,
      options: [{ value: NONE_SELECT_VALUE, label: "请选择 Program" }, ...programOptions],
    },
    {
      key: "description",
      label: "项目说明",
      type: "textarea",
      placeholder: "杂交项目目标、范围、批次安排等",
      colSpan: 2,
    },
  ], [programOptions]);

  const renderQueryForm = useCallback(() => (
    <div className="rounded-xl border border-slate-200 bg-white p-4 dark:border-slate-800 dark:bg-slate-950">
      <div className="grid gap-3 md:grid-cols-2">
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">关键词</Label>
          <Input
            value={draftQuery.keyword ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, keyword: event.target.value }))}
            placeholder="项目名称 / 说明模糊匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">Program</Label>
          <Select
            value={draftQuery.program_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, program_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部 Program" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部 Program</SelectItem>
              {programOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>
      <div className="mt-3 flex flex-wrap gap-2">
        <Button type="button" variant="outline" className="gap-2" onClick={() => {
          const reset = emptyQuery();
          setDraftQuery(reset);
          setAppliedQuery(reset);
        }}>
          <RotateCcw className="h-4 w-4" />
          重置
        </Button>
        <Button type="button" className="gap-2" onClick={() => setAppliedQuery({ ...draftQuery })}>
          <Search className="h-4 w-4" />
          查询
        </Button>
      </div>
    </div>
  ), [draftQuery, programOptions]);

  return (
    <BrapiEntityPage
      icon={Network}
      iconBg="bg-gradient-to-br from-lime-500 to-green-600"
      title="CrossingProject 杂交项目"
      description="crossing_project：某 Program 下的一组杂交任务集合（杂交工作台）。点击进入详情可查看下属 Cross 与 Pedigree Node。"
      addLabel="新增杂交项目"
      useEnhancedDialog
      fetchRecord={fetchRecord}
      renderQueryForm={renderQueryForm}
      columns={[
        { key: "crossingProjectDbId", label: "项目 ID" },
        {
          key: "name",
          label: "项目名称",
          render: (value, row) => {
            const id = String(row.id ?? row.crossingProjectDbId ?? "");
            const name = String(value ?? "—");
            if (!id) return name;
            return (
              <Link
                href={`/germplasm/cross-pedigree/projects/${encodeURIComponent(id)}`}
                className="font-medium text-lime-600 hover:underline dark:text-lime-400"
              >
                {name}
              </Link>
            );
          },
        },
        { key: "program_name", label: "Program" },
        {
          key: "description",
          label: "说明",
          render: (value) => {
            const text = String(value ?? "").trim();
            if (!text) return "—";
            return text.length > 48 ? `${text.slice(0, 48)}…` : text;
          },
        },
      ]}
      fields={fields}
      data={[]}
      stats={[
        {
          label: "/brapi/v2/crossingprojects",
          value: "BrAPI",
          className: "bg-lime-50 text-lime-700 dark:bg-lime-400/10 dark:text-lime-200",
        },
      ]}
      loadData={loadRows}
      createRecord={(payload) => createCrossingProjectRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updateCrossingProjectRow(id, payload) as unknown as Promise<Record<string, unknown>>}
    />
  );
}
