import type { BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import {
  optionOrNone,
  resolveContextFromStudy,
  resolveContextFromTrial,
  SAMPLE_TYPE_OPTIONS,
  type StudyContextOption,
  type TrialContextOption,
} from "../plateUtils";
import {
  buildWellFromRowColumn,
  resolveContextFromObservationUnit,
  resolveContextFromPlate,
  TISSUE_TYPE_OPTIONS,
  type ObservationUnitContextOption,
} from "../sampleUtils";
import { NONE_SELECT_VALUE, type PlateRecord, type SelectOption } from "../types";

export interface SampleFormOptions {
  programOptions: SelectOption[];
  trialOptions: TrialContextOption[];
  studyOptions: StudyContextOption[];
  germplasmOptions: SelectOption[];
  observationUnitOptions: ObservationUnitContextOption[];
  plateOptions: SelectOption[];
  personOptions: SelectOption[];
  plates: PlateRecord[];
  hidePlateField?: boolean;
}

export function buildSampleFields(options: SampleFormOptions): BrapiFormField[] {
  const fields: BrapiFormField[] = [
    { key: "sample_name", label: "样本名称", type: "text", required: true, placeholder: "如 华占-叶样-001" },
    { key: "sample_barcode", label: "样本条码", type: "text", placeholder: "扫码或手填，建议唯一" },
    { key: "sample_pui", label: "样本永久标识 (PUI)", type: "text", placeholder: "DOI / URL / UUID" },
    { key: "sample_group_db_id", label: "样本分组 ID", type: "text", placeholder: "可选" },
    { key: "sample_type", label: "样本类型", type: "select", options: SAMPLE_TYPE_OPTIONS },
    { key: "tissue_type", label: "组织类型", type: "select", options: TISSUE_TYPE_OPTIONS },
    { key: "sample_timestamp", label: "取样时间", type: "date" },
    {
      key: "taken_by",
      label: "取样人",
      type: "select",
      options: optionOrNone("未指定", options.personOptions),
    },
    {
      key: "program_id",
      label: "所属项目",
      type: "select",
      options: optionOrNone("不关联项目", options.programOptions),
    },
    {
      key: "trial_id",
      label: "所属 Trial",
      type: "select",
      options: optionOrNone("不关联 Trial", options.trialOptions),
    },
    {
      key: "study_id",
      label: "所属 Study",
      type: "select",
      options: optionOrNone("不关联 Study", options.studyOptions),
    },
    {
      key: "germplasm_id",
      label: "种质",
      type: "select",
      options: optionOrNone("不关联种质", options.germplasmOptions),
    },
    {
      key: "observation_unit_id",
      label: "观测单元",
      type: "select",
      options: optionOrNone("不关联观测单元", options.observationUnitOptions),
    },
  ];

  if (!options.hidePlateField) {
    fields.push({
      key: "plate_id",
      label: "所在样本板",
      type: "select",
      options: optionOrNone("未上板", options.plateOptions),
    });
  }

  fields.push(
    { key: "row", label: "板行", type: "text", placeholder: "A–H（96 孔板）" },
    { key: "column", label: "板列", type: "number", placeholder: "1–12" },
    { key: "well", label: "孔位", type: "text", placeholder: "如 A01，可留空由行/列自动生成" },
    { key: "sample_description", label: "样本说明", type: "textarea", colSpan: 2 },
  );

  return fields;
}

export function createSampleFormExtraHandlers(options: SampleFormOptions) {
  return (props: {
    formData: Record<string, unknown>;
    updateForm: (key: string, value: string) => void;
    updateFormBatch: (patch: Record<string, unknown>) => void;
  }) => {
    const handleStudyChange = (value: string) => {
      const context = resolveContextFromStudy(value === NONE_SELECT_VALUE ? null : value, options.studyOptions);
      props.updateFormBatch({
        study_id: value,
        trial_id: context.trial_id,
        program_id: context.program_id,
      });
    };

    const handleTrialChange = (value: string) => {
      const context = resolveContextFromTrial(value === NONE_SELECT_VALUE ? null : value, options.trialOptions);
      props.updateFormBatch({
        trial_id: value,
        program_id: context.program_id,
      });
    };

    const handlePlateChange = (value: string) => {
      const plateId = value === NONE_SELECT_VALUE ? null : value;
      const context = resolveContextFromPlate(plateId, options.plates);
      props.updateFormBatch({
        plate_id: value,
        program_id: context.program_id,
        trial_id: context.trial_id,
        study_id: context.study_id,
      });
    };

    const handleObservationUnitChange = (value: string) => {
      const unitId = value === NONE_SELECT_VALUE ? null : value;
      const context = resolveContextFromObservationUnit(unitId, options.observationUnitOptions);
      props.updateFormBatch({
        observation_unit_id: value,
        study_id: context.study_id,
      });
    };

    const handleRowColumnChange = (key: "row" | "column", value: string) => {
      const nextRow = key === "row" ? value : String(props.formData.row ?? "");
      const nextColumn = key === "column" ? value : String(props.formData.column ?? "");
      const autoWell = buildWellFromRowColumn(nextRow, nextColumn);
      if (autoWell && !String(props.formData.well ?? "").trim()) {
        props.updateFormBatch({ [key]: value, well: autoWell });
      } else {
        props.updateForm(key, value);
      }
    };

    return {
      handleStudyChange,
      handleTrialChange,
      handlePlateChange,
      handleObservationUnitChange,
      handleRowColumnChange,
    };
  };
}
