"use client";

import Link from "next/link";
import { useCallback, useMemo } from "react";
import { GitFork, Package } from "lucide-react";
import { BrapiEntityPage } from "@/components/brapi/BrapiEntityPage";
import { Button } from "@/components/ui/button";
import { fetchCrossParentRows } from "../../cross-pedigree/api";
import { parentTypeLabel } from "../../cross-pedigree/constants";
import { fetchSeedLotRows } from "../../seed-lot/api";
import type { SeedLotRecord } from "../../seed-lot/types";
import { GermplasmAttributeValueTab } from "./GermplasmAttributeValueTab";
export { GermplasmPedigreePanel } from "./GermplasmPedigreePanel";

interface RelatedPanelProps {
  germplasmDbId: string;
}

function seedLotContainsGermplasm(row: SeedLotRecord, germplasmDbId: string) {
  const mixtures = row.content_mixture ?? row.contentMixture ?? [];
  return mixtures.some((item) => (item.germplasm_id ?? item.germplasmDbId) === germplasmDbId);
}

export function GermplasmAttributePanel({ germplasmDbId }: RelatedPanelProps) {
  return <GermplasmAttributeValueTab scopeGermplasmDbId={germplasmDbId} />;
}

export function GermplasmSeedLotPanel({ germplasmDbId }: RelatedPanelProps) {
  const loadRows = useCallback(async () => {
    const rows = await fetchSeedLotRows();
    return rows
      .filter((row) => seedLotContainsGermplasm(row, germplasmDbId))
      .map((row) => row as unknown as Record<string, unknown>);
  }, [germplasmDbId]);

  const columns = useMemo(() => [
    {
      key: "name",
      label: "批次名称",
      render: (value: unknown, row: Record<string, unknown>) => {
        const id = String(row.id ?? "");
        const name = String(value ?? row.seed_lot_name ?? "—");
        if (!id) return name;
        return (
          <Link
            href={`/germplasm/seed-lot/${encodeURIComponent(id)}?tab=mixture`}
            className="font-medium text-emerald-600 hover:underline dark:text-emerald-400"
          >
            {name}
          </Link>
        );
      },
    },
    { key: "amount", label: "数量" },
    { key: "units", label: "单位" },
    { key: "location_name", label: "库位" },
    { key: "program_name", label: "Program" },
  ], []);

  return (
    <div className="space-y-3">
      <Button asChild variant="outline" size="sm" className="w-fit">
        <Link href="/germplasm/seed-lot?tab=lots">
          <Package className="mr-2 h-4 w-4" />
          在 Seed Lot 页维护
        </Link>
      </Button>
      <BrapiEntityPage
        icon={Package}
        iconBg="bg-gradient-to-br from-amber-500 to-orange-600"
        title="Seed Lot 库存批次"
        description="content_mixture 中包含当前种质的 seed_lot 批次；点击名称进入批次详情维护组成。"
        columns={columns}
        fields={[]}
        data={[]}
        loadData={loadRows}
      />
    </div>
  );
}

export function GermplasmCrossParentPanel({ germplasmDbId }: RelatedPanelProps) {
  const loadRows = useCallback(async () => {
    const rows = await fetchCrossParentRows();
    return rows
      .filter((row) => row.germplasm_id === germplasmDbId)
      .map((row) => ({
        ...row,
        parent_type_label: row.parent_type ? parentTypeLabel(row.parent_type) : "—",
      })) as unknown as Record<string, unknown>[];
  }, [germplasmDbId]);

  const columns = useMemo(() => [
    { key: "cross_name", label: "Cross" },
    { key: "planned", label: "Planned", render: (value: unknown) => (value ? "是" : "否") },
    { key: "parent_slot", label: "亲本槽位" },
    { key: "parent_type_label", label: "亲本类型" },
    { key: "crossing_project_name", label: "杂交项目" },
  ], []);

  return (
    <div className="space-y-3">
      <Button asChild variant="outline" size="sm" className="w-fit">
        <Link href="/germplasm/cross-pedigree?tab=parents">
          <GitFork className="mr-2 h-4 w-4" />
          在 Cross Parent 页维护
        </Link>
      </Button>
      <BrapiEntityPage
        icon={GitFork}
        iconBg="bg-gradient-to-br from-rose-500 to-pink-600"
        title="Cross Parent 亲本记录"
        description="当前种质作为亲本参与的 cross / planned cross 记录（只读列表）。"
        columns={columns}
        fields={[]}
        data={[]}
        loadData={loadRows}
      />
    </div>
  );
}
