"use client";

import { useCallback, useMemo } from "react";
import { Building2, Hash, MapPin, Tags } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import {
  createDonorRow,
  createInstituteRow,
  createOriginRow,
  createSynonymRow,
  createTaxonRow,
  deleteDonorRow,
  deleteInstituteRow,
  deleteOriginRow,
  deleteSynonymRow,
  deleteTaxonRow,
  fetchDonorRecord,
  fetchDonorRows,
  fetchInstituteRecord,
  fetchInstituteRows,
  fetchOriginRecord,
  fetchOriginRows,
  fetchSynonymRecord,
  fetchSynonymRows,
  fetchTaxonRecord,
  fetchTaxonRows,
  updateDonorRow,
  updateInstituteRow,
  updateOriginRow,
  updateSynonymRow,
  updateTaxonRow,
} from "../profileApi";
import { INSTITUTE_TYPE_OPTIONS } from "../profileTypes";

interface ProfilePanelProps {
  germplasmDbId: string;
}

function useProfileMutations<T>(
  germplasmDbId: string,
  loadRows: (id: string) => Promise<T[]>,
  createRow: (id: string, payload: Record<string, unknown>) => Promise<unknown>,
  updateRow: (id: string, rowId: string, payload: Record<string, unknown>) => Promise<unknown>,
  deleteRow: (id: string, rowId: string) => Promise<unknown>,
) {
  const loadData = useCallback(async () => {
    const rows = await loadRows(germplasmDbId);
    return rows as unknown as Record<string, unknown>[];
  }, [germplasmDbId, loadRows]);

  const wrap = useCallback(<R, >(action: () => Promise<R>) => action(), []);

  return {
    loadData,
    createRecord: (payload: Record<string, unknown>) => wrap(() => createRow(germplasmDbId, payload)) as Promise<Record<string, unknown>>,
    updateRecord: (id: string, payload: Record<string, unknown>) => wrap(() => updateRow(germplasmDbId, id, payload)) as Promise<Record<string, unknown>>,
    deleteRecord: (id: string) => wrap(() => deleteRow(germplasmDbId, id)).then(() => undefined),
  };
}

export function GermplasmDonorPanel({ germplasmDbId }: ProfilePanelProps) {
  const mutations = useProfileMutations(
    germplasmDbId,
    fetchDonorRows,
    createDonorRow,
    updateDonorRow,
    deleteDonorRow,
  );

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "donor_accession_number", label: "Donor Accession", type: "text", placeholder: "捐赠方登录号" },
    { key: "donor_institute_code", label: "Donor 机构代码", type: "text", placeholder: "如 USA999" },
    { key: "germplasmpui", label: "Germplasm PUI", type: "text", placeholder: "捐赠方 PUI" },
  ], []);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={Building2}
      iconBg="bg-gradient-to-br from-sky-500 to-blue-600"
      title="Donor 捐赠方"
      description="维护 germplasm_donor；同一材料可有多条捐赠方记录。"
      addLabel="新增 Donor"
      columns={[
        { key: "donor_accession_number", label: "Accession" },
        { key: "donor_institute_code", label: "机构代码" },
        { key: "germplasmpui", label: "PUI" },
      ]}
      fields={fields}
      data={[]}
      {...mutations}
      fetchRecord={(id) => fetchDonorRecord(germplasmDbId, id) as Promise<Record<string, unknown>>}
    />
  );
}

export function GermplasmInstitutePanel({ germplasmDbId }: ProfilePanelProps) {
  const mutations = useProfileMutations(
    germplasmDbId,
    fetchInstituteRows,
    createInstituteRow,
    updateInstituteRow,
    deleteInstituteRow,
  );

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "Institute ID", type: "text", placeholder: "留空则系统自动生成" },
    {
      key: "institute_type",
      label: "机构类型",
      type: "select",
      required: true,
      options: INSTITUTE_TYPE_OPTIONS.map((item) => ({ value: item.value, label: item.label })),
    },
    { key: "institute_code", label: "机构代码", type: "text", placeholder: "如 USA999" },
    { key: "institute_name", label: "机构名称", type: "text", required: true, placeholder: "机构全称" },
    { key: "institute_address", label: "机构地址", type: "textarea", colSpan: 2 },
  ], []);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={Building2}
      iconBg="bg-gradient-to-br from-indigo-500 to-violet-600"
      title="Institute 机构"
      description="维护 germplasm_institute；支持 HOST / DONOR / BREEDING / COLLECTING / REDUNDANT。"
      addLabel="新增机构"
      columns={[
        { key: "institute_type", label: "类型" },
        { key: "institute_code", label: "代码" },
        { key: "institute_name", label: "名称" },
        { key: "institute_address", label: "地址" },
      ]}
      fields={fields}
      data={[]}
      {...mutations}
      fetchRecord={(id) => fetchInstituteRecord(germplasmDbId, id) as Promise<Record<string, unknown>>}
    />
  );
}

export function GermplasmOriginPanel({ germplasmDbId }: ProfilePanelProps) {
  const mutations = useProfileMutations(
    germplasmDbId,
    fetchOriginRows,
    createOriginRow,
    updateOriginRow,
    deleteOriginRow,
  );

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "longitude", label: "经度", type: "number", placeholder: "WGS84 经度" },
    { key: "latitude", label: "纬度", type: "number", placeholder: "WGS84 纬度" },
    { key: "coordinate_uncertainty", label: "坐标不确定性 (m)", type: "text", placeholder: "可选" },
  ], []);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={MapPin}
      iconBg="bg-gradient-to-br from-emerald-500 to-teal-600"
      title="Origin 来源坐标"
      description="维护 germplasm_origin；以 WGS84 点坐标保存 GeoJSON。"
      addLabel="新增 Origin"
      columns={[
        { key: "longitude", label: "经度" },
        { key: "latitude", label: "纬度" },
        { key: "coordinate_uncertainty", label: "不确定性" },
      ]}
      fields={fields}
      data={[]}
      {...mutations}
      fetchRecord={(id) => fetchOriginRecord(germplasmDbId, id) as Promise<Record<string, unknown>>}
    />
  );
}

export function GermplasmSynonymPanel({ germplasmDbId }: ProfilePanelProps) {
  const mutations = useProfileMutations(
    germplasmDbId,
    fetchSynonymRows,
    createSynonymRow,
    updateSynonymRow,
    deleteSynonymRow,
  );

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "synonym", label: "别名", type: "text", required: true, placeholder: "别名 / 旧名 / 本地名" },
    { key: "type", label: "类型", type: "text", placeholder: "如 local / commercial / old name" },
  ], []);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={Tags}
      iconBg="bg-gradient-to-br from-amber-500 to-orange-600"
      title="Synonym 别名"
      description="维护 germplasm_synonym；列表搜索会命中 alias。"
      addLabel="新增别名"
      columns={[
        { key: "synonym", label: "别名" },
        { key: "type", label: "类型" },
      ]}
      fields={fields}
      data={[]}
      {...mutations}
      fetchRecord={(id) => fetchSynonymRecord(germplasmDbId, id) as Promise<Record<string, unknown>>}
    />
  );
}

export function GermplasmTaxonPanel({ germplasmDbId }: ProfilePanelProps) {
  const mutations = useProfileMutations(
    germplasmDbId,
    fetchTaxonRows,
    createTaxonRow,
    updateTaxonRow,
    deleteTaxonRow,
  );

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "source_name", label: "来源体系", type: "text", placeholder: "如 NCBI Taxonomy" },
    { key: "taxon_id", label: "Taxon ID", type: "text", required: true, placeholder: "外部 taxon 标识" },
  ], []);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={Hash}
      iconBg="bg-gradient-to-br from-rose-500 to-pink-600"
      title="Taxon 分类标识"
      description="维护 germplasm_taxon；Sample 可引用 taxon 记录。"
      addLabel="新增 Taxon"
      columns={[
        { key: "source_name", label: "来源" },
        { key: "taxon_id", label: "Taxon ID" },
      ]}
      fields={fields}
      data={[]}
      {...mutations}
      fetchRecord={(id) => fetchTaxonRecord(germplasmDbId, id) as Promise<Record<string, unknown>>}
    />
  );
}

export function GermplasmProfileSummaryHint() {
  return (
    <div className="rounded-lg border border-teal-100 bg-teal-50/60 px-3 py-2 text-xs text-teal-900 dark:border-teal-900/40 dark:bg-teal-950/30 dark:text-teal-100">
      Donor / Origin / Synonym / Taxon 通过 BrAPI `PUT /germplasm/{id}` 整表替换保存；Institute 使用扩展接口单独维护。
    </div>
  );
}
