"use client";

import Link from "next/link";
import { useCallback, useMemo, useState } from "react";
import { Package, 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 {
  createSeedLotRow,
  deleteSeedLotRow,
  fetchSeedLotDetail,
  fetchSeedLotOptions,
  fetchSeedLotRows,
  mapContentMixtureToForm,
  normalizeSeedLotFormData,
  updateSeedLotMetadata,
} from "../api";
import { ContentMixtureEditor } from "./ContentMixtureEditor";
import {
  NONE_SELECT_VALUE,
  STOCK_STATUS_LABEL,
  resolveStockStatus,
  type ContentMixtureRow,
  type SeedLotQuery,
  type SelectOption,
  type StockStatus,
} from "../types";

const unitOptions: SelectOption[] = [
  { value: "seeds", label: "seeds 粒" },
  { value: "g", label: "g 克" },
  { value: "kg", label: "kg 千克" },
  { value: "plants", label: "plants 株" },
  { value: "bag", label: "bag 袋" },
  { value: "tube", label: "tube 管" },
];

const stockStatusOptions: SelectOption[] = [
  { value: NONE_SELECT_VALUE, label: "全部状态" },
  { value: "sufficient", label: STOCK_STATUS_LABEL.sufficient },
  { value: "low", label: STOCK_STATUS_LABEL.low },
  { value: "depleted", label: STOCK_STATUS_LABEL.depleted },
];

const emptyQuery = (): SeedLotQuery => ({
  program_id: NONE_SELECT_VALUE,
  location_id: NONE_SELECT_VALUE,
  name: "",
  stock_status: NONE_SELECT_VALUE,
});

function StockStatusBadge({ amount }: { amount: unknown }) {
  const status = resolveStockStatus(typeof amount === "number" ? amount : Number(amount ?? 0));
  const className = status === "depleted"
    ? "bg-red-50 text-red-700 dark:bg-red-400/10 dark:text-red-200"
    : status === "low"
      ? "bg-amber-50 text-amber-700 dark:bg-amber-400/10 dark:text-amber-200"
      : "bg-emerald-50 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-200";
  return <Badge variant="outline" className={className}>{STOCK_STATUS_LABEL[status]}</Badge>;
}

export function SeedLotTab() {
  const [locationOptions, setLocationOptions] = useState<SelectOption[]>([]);
  const [programOptions, setProgramOptions] = useState<SelectOption[]>([]);
  const [germplasmOptions, setGermplasmOptions] = useState<SelectOption[]>([]);
  const [crossOptions, setCrossOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<SeedLotQuery>(emptyQuery);
  const [appliedQuery, setAppliedQuery] = useState<SeedLotQuery>(emptyQuery);

  const applyOptions = useCallback((options: Awaited<ReturnType<typeof fetchSeedLotOptions>>) => {
    setLocationOptions(options.locations);
    setProgramOptions(options.programs);
    setGermplasmOptions(options.germplasms);
    setCrossOptions(options.crosses);
    return options;
  }, []);

  const normalizedQuery = useMemo((): SeedLotQuery => ({
    ...appliedQuery,
    program_id: appliedQuery.program_id === NONE_SELECT_VALUE ? undefined : appliedQuery.program_id,
    location_id: appliedQuery.location_id === NONE_SELECT_VALUE ? undefined : appliedQuery.location_id,
    stock_status: appliedQuery.stock_status === NONE_SELECT_VALUE
      ? undefined
      : appliedQuery.stock_status as StockStatus | undefined,
  }), [appliedQuery]);

  const loadRows = useCallback(async () => {
    const [options, rows] = await Promise.all([
      fetchSeedLotOptions(),
      fetchSeedLotRows(normalizedQuery),
    ]);
    applyOptions(options);
    return rows as unknown as Record<string, unknown>[];
  }, [applyOptions, normalizedQuery]);

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

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "name", label: "批次名称", type: "text", required: true, placeholder: "如 华占-2026-荆门-扩繁批" },
    {
      key: "units",
      label: "数量单位",
      type: "select",
      required: true,
      options: unitOptions,
    },
    {
      key: "program_id",
      label: "所属项目",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联项目" }, ...programOptions],
    },
    {
      key: "location_id",
      label: "存放地点",
      type: "select",
      options: [{ value: NONE_SELECT_VALUE, label: "不关联地点" }, ...locationOptions],
    },
    { key: "storage_location", label: "库位描述", type: "text", placeholder: "如 冰箱A-2层-盒03" },
    { key: "source_collection", label: "来源集合", type: "text", placeholder: "如 野外采集 / nursery / 种质库集合" },
    { key: "created_date", label: "创建日期", type: "date" },
    { key: "seed_lot_description", label: "批次说明", type: "textarea", placeholder: "材料来源、处理方式、入库备注等", colSpan: 2 },
  ], [locationOptions, 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 lg:grid-cols-4">
        <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 position="popper" className="z-[110] max-h-60">
              <SelectItem value={NONE_SELECT_VALUE}>全部项目</SelectItem>
              {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">地点</Label>
          <Select
            value={draftQuery.location_id ?? NONE_SELECT_VALUE}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, location_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部地点" /></SelectTrigger>
            <SelectContent position="popper" className="z-[110] max-h-60">
              <SelectItem value={NONE_SELECT_VALUE}>全部地点</SelectItem>
              {locationOptions.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">批次名称</Label>
          <Input
            value={draftQuery.name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({ ...current, name: event.target.value }))}
            placeholder="名称子串匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">库存状态</Label>
          <Select
            value={String(draftQuery.stock_status ?? NONE_SELECT_VALUE)}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, stock_status: value as SeedLotQuery["stock_status"] }))}
          >
            <SelectTrigger><SelectValue placeholder="全部状态" /></SelectTrigger>
            <SelectContent position="popper" className="z-[110]">
              {stockStatusOptions.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, locationOptions, programOptions]);

  const renderFormExtra = useCallback((props: {
    formData: Record<string, unknown>;
    updateForm: (key: string, value: string) => void;
    updateFormBatch: (patch: Record<string, unknown>) => void;
    editingRow: Record<string, unknown> | null;
  }) => {
    const isEditing = Boolean(props.editingRow);
    const seedLotId = String(props.editingRow?.id ?? "");
    const mixtureRows = Array.isArray(props.formData.content_mixture)
      ? props.formData.content_mixture as ContentMixtureRow[]
      : mapContentMixtureToForm([]);

    const handlePrimaryGermplasmChange = (value: string) => {
      props.updateForm("primary_germplasm_id", value);
      if (!isEditing && value !== NONE_SELECT_VALUE) {
        props.updateFormBatch({
          primary_germplasm_id: value,
          content_mixture: [{ germplasm_id: value, cross_id: NONE_SELECT_VALUE, mixture_percentage: "100" }],
        });
      }
    };

    return (
      <>
        {isEditing ? (
          <div>
            <Label className="mb-1.5 block text-sm text-slate-700 dark:text-slate-200">批次 ID（只读）</Label>
            <Input value={seedLotId || "—"} readOnly className="bg-slate-50 dark:bg-slate-900" />
          </div>
        ) : null}

        {!isEditing ? (
          <div>
            <Label className="mb-1.5 block text-sm text-slate-700 dark:text-slate-200">快捷主材料</Label>
            <Select
              value={String(props.formData.primary_germplasm_id ?? NONE_SELECT_VALUE)}
              onValueChange={handlePrimaryGermplasmChange}
            >
              <SelectTrigger><SelectValue placeholder="选择单个 germplasm 可自动生成 100% 组成" /></SelectTrigger>
              <SelectContent position="popper" className="z-[110] max-h-60">
                <SelectItem value={NONE_SELECT_VALUE}>不自动填充组成</SelectItem>
                {germplasmOptions.map((option) => (
                  <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p className="mt-1 text-xs text-slate-500">新建时选择主材料将自动生成一条 100% 批次组成；也可创建后在详情页维护。</p>
          </div>
        ) : null}

        <div>
          <Label className="mb-1.5 block text-sm text-slate-700 dark:text-slate-200">
            {isEditing ? "当前库存（只读）" : "初始库存数量"}
          </Label>
          {isEditing ? (
            <Input value={String(props.formData.amount ?? "0")} readOnly className="bg-slate-50 dark:bg-slate-900" />
          ) : (
            <Input
              type="number"
              min={0}
              value={String(props.formData.amount ?? "")}
              onChange={(event) => props.updateForm("amount", event.target.value)}
              placeholder="可选；建议后续通过「库存交易」入库"
            />
          )}
          <p className="mt-1 text-xs text-slate-500">
            {isEditing ? "库存数量请通过「库存交易」更新。" : "也可创建后在「库存交易」中执行入库。"}
          </p>
        </div>

        {isEditing ? (
          <div>
            <Label className="mb-1.5 block text-sm text-slate-700 dark:text-slate-200">最后更新（只读）</Label>
            <Input value={String(props.formData.last_updated ?? "—")} readOnly className="bg-slate-50 dark:bg-slate-900" />
          </div>
        ) : null}

        {isEditing && seedLotId ? (
          <div className="md:col-span-2 rounded-lg border border-lime-100 bg-lime-50/60 p-3 text-sm text-lime-900 dark:border-lime-900/40 dark:bg-lime-950/30 dark:text-lime-100">
            批次组成请在
            {" "}
            <Link
              href={`/germplasm/seed-lot/${encodeURIComponent(seedLotId)}?tab=mixture`}
              className="font-medium underline"
            >
              批次详情 → Content Mixture
            </Link>
            {" "}
            Tab 中维护。
          </div>
        ) : (
          <ContentMixtureEditor
            rows={mixtureRows}
            germplasmOptions={germplasmOptions}
            crossOptions={crossOptions}
            onChange={(rows) => props.updateFormBatch({ content_mixture: rows })}
          />
        )}
      </>
    );
  }, [crossOptions, germplasmOptions]);

  return (
    <BrapiEntityPage
      icon={Package}
      iconBg="bg-gradient-to-br from-lime-500 to-green-600"
      title="SeedLot 种子批次"
      description="维护种子或材料库存批次；组成在详情页维护，库存数量通过交易更新"
      addLabel="新增批次"
      useEnhancedDialog
      fetchRecord={fetchRecord}
      renderQueryForm={() => renderQueryForm()}
      renderFormExtra={renderFormExtra}
      columns={[
        { key: "id", label: "批次 ID" },
        {
          key: "name",
          label: "批次名称",
          render: (value, row) => {
            const id = String(row.id ?? "");
            const name = String(value ?? "—");
            if (!id) return name;
            return (
              <Link
                href={`/germplasm/seed-lot/${encodeURIComponent(id)}`}
                className="font-medium text-lime-600 hover:underline dark:text-lime-400"
              >
                {name}
              </Link>
            );
          },
        },
        {
          key: "stock_status",
          label: "库存状态",
          render: (_, row) => <StockStatusBadge amount={row.amount} />,
        },
        {
          key: "amount",
          label: "库存",
          render: (value, row) => {
            const amount = value ?? "—";
            const units = row.units ? ` ${String(row.units)}` : "";
            return `${amount}${units}`;
          },
        },
        {
          key: "mixture_summary",
          label: "批次组成",
          render: (_, row) => {
            const mixtures = (row.content_mixture ?? row.contentMixture) as Array<Record<string, unknown>> | undefined;
            if (!mixtures?.length) return "—";
            return mixtures.map((mixture, index) => {
              const germplasmId = String(mixture.germplasmDbId ?? mixture.germplasm_id ?? "");
              const label = mixture.germplasmName || mixture.germplasm_name || mixture.crossName || mixture.cross_name || "未知";
              const percentage = mixture.mixturePercentage ?? mixture.mixture_percentage;
              const text = `${label}${percentage != null ? ` (${percentage}%)` : ""}`;
              if (germplasmId && germplasmId !== NONE_SELECT_VALUE) {
                return (
                  <span key={`${germplasmId}-${index}`}>
                    {index > 0 ? "；" : ""}
                    <Link
                      href={`/germplasm/germplasm/${encodeURIComponent(germplasmId)}?tab=seed-lots`}
                      className="font-medium text-teal-600 hover:underline dark:text-teal-400"
                    >
                      {text}
                    </Link>
                  </span>
                );
              }
              return `${index > 0 ? "；" : ""}${text}`;
            });
          },
        },
        { key: "program_name", label: "项目" },
        { key: "location_name", label: "地点" },
        { key: "storage_location", label: "库位" },
        { key: "source_collection", label: "来源集合" },
        { key: "last_updated", label: "最后更新" },
      ]}
      fields={fields}
      data={[]}
      stats={[
        { label: "/brapi/v2/seedlots", value: "BrAPI", className: "bg-lime-50 text-lime-700 dark:bg-lime-400/10 dark:text-lime-200" },
        { label: "contentMixture", value: "PUT/POST", className: "bg-emerald-50 text-emerald-700 dark:bg-emerald-400/10 dark:text-emerald-200" },
      ]}
      loadData={loadRows}
      createRecord={async (payload) => {
        const normalized = {
          ...payload,
          content_mixture: payload.content_mixture ?? mapContentMixtureToForm([]),
        };
        return createSeedLotRow(normalized) as unknown as Promise<Record<string, unknown>>;
      }}
      updateRecord={async (id, payload) => updateSeedLotMetadata(id, payload) as unknown as Promise<Record<string, unknown>>}
      deleteRecord={deleteSeedLotRow}
    />
  );
}
