"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { ClipboardList, RotateCcw, Search } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { Badge } from "@/components/ui/badge";
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 {
  createPlateRow,
  fetchPlateDetail,
  loadSamplePlatePageData,
  normalizePlateFormData,
  updatePlateRow,
} from "../api";
import {
  optionLabel,
  optionOrNone,
  PLATE_FORMAT_OPTIONS,
  SAMPLE_TYPE_OPTIONS,
  type StudyContextOption,
  type TrialContextOption,
} from "../plateUtils";
import { NONE_SELECT_VALUE, type PlateQuery, type SelectOption } from "../types";

const emptyQuery = (): PlateQuery => ({
  plate_name: "",
  plate_barcode: "",
  program_id: NONE_SELECT_VALUE,
  trial_id: NONE_SELECT_VALUE,
  study_id: NONE_SELECT_VALUE,
});

export function PlateTab() {
  const [programOptions, setProgramOptions] = useState<SelectOption[]>([]);
  const [trialOptions, setTrialOptions] = useState<TrialContextOption[]>([]);
  const [studyOptions, setStudyOptions] = useState<StudyContextOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<PlateQuery>(emptyQuery);
  const [appliedQuery, setAppliedQuery] = useState<PlateQuery>(emptyQuery);

  const applyOptions = useCallback((options: Awaited<ReturnType<typeof loadSamplePlatePageData>>["options"]) => {
    setProgramOptions(options.programs);
    setTrialOptions(options.trials);
    setStudyOptions(options.studies);
    return options;
  }, []);

  const loadRows = useCallback(async () => {
    const { options, plates } = await loadSamplePlatePageData({ plateQuery: appliedQuery });
    applyOptions(options);
    return plates as unknown as Record<string, unknown>[];
  }, [appliedQuery, applyOptions]);

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

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "plate_name", label: "样本板名称", type: "text", required: true, placeholder: "如 2026-华占-96孔板-01" },
    { key: "plate_barcode", label: "样本板条码", type: "text", placeholder: "扫码或手填，建议唯一" },
    { key: "plate_format", label: "板规格", type: "select", options: PLATE_FORMAT_OPTIONS },
    { key: "sample_type", label: "样本类型", type: "select", options: SAMPLE_TYPE_OPTIONS },
    {
      key: "program_id",
      label: "所属项目",
      type: "select",
      options: optionOrNone("不关联项目", programOptions),
    },
    {
      key: "trial_id",
      label: "所属 Trial",
      type: "select",
      options: optionOrNone("不关联 Trial", trialOptions),
    },
    {
      key: "study_id",
      label: "所属 Study",
      type: "select",
      options: optionOrNone("不关联 Study", studyOptions),
    },
  ], [programOptions, studyOptions, trialOptions]);

  const renderFormExtra = useCallback(() => (
    <div className="col-span-2 rounded-lg border border-amber-100 bg-amber-50/60 p-3 text-xs text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-100">
      <p className="font-medium">Core 上下文与孔位校验</p>
      <p className="mt-1 text-amber-800/80 dark:text-amber-200/80">
        若同时填写 Program / Trial / Study，保存时会校验层级一致性。选择 96 孔板后，下属样本的行/列/孔位将在录入时校验（A–H，列 1–12）。
      </p>
    </div>
  ), []);

  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 xl:grid-cols-5">
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">样本板名称</Label>
          <Input
            value={draftQuery.plate_name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, plate_name: event.target.value }))}
            placeholder="plateName 模糊匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">样本板条码</Label>
          <Input
            value={draftQuery.plate_barcode ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, plate_barcode: event.target.value }))}
            placeholder="barcode 模糊匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">项目</Label>
          <Select
            value={draftQuery.program_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, program_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              {optionOrNone("全部项目", programOptions).map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">Trial</Label>
          <Select
            value={draftQuery.trial_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, trial_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              {optionOrNone("全部 Trial", trialOptions).map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">Study</Label>
          <Select
            value={draftQuery.study_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, study_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部" /></SelectTrigger>
            <SelectContent>
              {optionOrNone("全部 Study", studyOptions).map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>
      <div className="mt-3 flex justify-end 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, studyOptions, trialOptions]);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={ClipboardList}
      iconBg="bg-gradient-to-br from-orange-500 to-amber-600"
      title="样本板管理"
      description="管理送检前的样本板：条码、规格、样本类型及 Program / Trial / Study 归属。点击进入详情可维护下属样本。"
      addLabel="新建样本板"
      columns={[
        {
          key: "plate_name",
          label: "样本板名称",
          render: (value, row) => {
            const id = String(row.id ?? row.plateDbId ?? "");
            const name = String(value ?? "—");
            if (!id) return name;
            return (
              <Link href={`/genotyping/sample-plate/plates/${encodeURIComponent(id)}`} className="font-medium text-orange-600 hover:underline dark:text-orange-400">
                {name}
              </Link>
            );
          },
        },
        { key: "plate_barcode", label: "条码" },
        { key: "plate_format", label: "规格", render: (value) => optionLabel(PLATE_FORMAT_OPTIONS, value) },
        { key: "sample_type", label: "样本类型", render: (value) => optionLabel(SAMPLE_TYPE_OPTIONS, value) },
        { key: "program_name", label: "项目" },
        { key: "trial_name", label: "Trial" },
        { key: "study_name", label: "Study" },
        {
          key: "sample_count",
          label: "样本数",
          render: (value) => {
            const count = Number(value ?? 0);
            return (
              <Badge variant="outline" className={count > 0 ? "border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200" : ""}>
                {count}
              </Badge>
            );
          },
        },
      ]}
      fields={fields}
      data={[]}
      stats={[{ label: "/brapi/v2/plates", value: "BrAPI", className: "bg-amber-50 text-amber-700 dark:bg-amber-400/10 dark:text-amber-200" }]}
      loadData={loadRows}
      fetchRecord={fetchRecord}
      createRecord={(payload) => createPlateRow(payload) as unknown as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => updatePlateRow(id, payload) as unknown as Promise<Record<string, unknown>>}
      renderQueryForm={() => renderQueryForm()}
      renderFormExtra={renderFormExtra}
    />
  );
}
