"use client";

import { useCallback, useMemo } from "react";
import { FlaskConical } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  createVariantSetAnalysisRow,
  deleteVariantSetAnalysisRow,
  fetchVariantSetAnalysisRows,
  normalizeVariantSetAnalysisFormData,
  updateVariantSetAnalysisRow,
} from "../api";
import { ANALYSIS_TYPE_OPTIONS, NONE_SELECT_VALUE } from "../types";

interface VariantSetAnalysisPanelProps {
  variantSetDbId: string;
  onChanged?: () => void;
}

const optionOrNone = (label: string, options: readonly { value: string; label: string }[]) => [
  { value: NONE_SELECT_VALUE, label },
  ...options,
];

export function VariantSetAnalysisPanel({ variantSetDbId, onChanged }: VariantSetAnalysisPanelProps) {
  const loadRows = useCallback(async () => {
    const rows = await fetchVariantSetAnalysisRows(variantSetDbId);
    return rows as unknown as Record<string, unknown>[];
  }, [variantSetDbId]);

  const findRowById = useCallback(async (id: string) => {
    const rows = await fetchVariantSetAnalysisRows(variantSetDbId);
    const row = rows.find((item) => item.id === id);
    if (!row) throw new Error("Analysis 不存在");
    return normalizeVariantSetAnalysisFormData(row);
  }, [variantSetDbId]);

  const wrapMutation = useCallback(<T,>(action: () => Promise<T>) => async () => {
    const result = await action();
    onChanged?.();
    return result;
  }, [onChanged]);

  const fields = useMemo<BrapiFormField[]>(() => [
    { key: "id", label: "Analysis ID", type: "text", placeholder: "留空则系统自动生成" },
    { key: "analysis_name", label: "分析名称", type: "text", required: true, placeholder: "如 Standard QC" },
    {
      key: "type",
      label: "分析类型",
      type: "select",
      options: optionOrNone("不指定类型", ANALYSIS_TYPE_OPTIONS),
    },
    { key: "description", label: "分析说明", type: "textarea", placeholder: "描述分析流程或 QC 标准" },
    { key: "created", label: "创建时间", type: "text", placeholder: "2024-01-01T12:00:00+08:00" },
    { key: "updated", label: "更新时间", type: "text", placeholder: "2024-01-01T12:00:00+08:00" },
  ], []);

  const columns = useMemo(() => [
    { key: "analysisName", label: "分析名称" },
    { key: "type", label: "类型" },
    {
      key: "software",
      label: "Software",
      render: (value: unknown) => {
        if (Array.isArray(value)) return value.length ? value.join(", ") : "—";
        return String(value ?? "—");
      },
    },
    {
      key: "description",
      label: "说明",
      render: (value: unknown) => {
        const text = String(value ?? "");
        if (!text) return "—";
        return text.length > 40 ? `${text.slice(0, 40)}…` : text;
      },
    },
  ], []);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={FlaskConical}
      iconBg="bg-gradient-to-br from-amber-500 to-orange-600"
      title="Analysis"
      description="维护 VariantSet 的分析或 QC 信息，每条记录可关联多个 software（名称、版本或 URL）。"
      addLabel="新增 Analysis"
      columns={columns}
      fields={fields}
      data={[]}
      loadData={loadRows}
      fetchRecord={findRowById}
      createRecord={(payload) => wrapMutation(() => createVariantSetAnalysisRow(variantSetDbId, payload))() as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => wrapMutation(() => updateVariantSetAnalysisRow(variantSetDbId, id, payload))() as Promise<Record<string, unknown>>}
      deleteRecord={(id) => wrapMutation(() => deleteVariantSetAnalysisRow(variantSetDbId, id))().then(() => undefined)}
      renderFormExtra={({ formData, updateForm }) => (
        <div className="col-span-2 space-y-1.5">
          <Label htmlFor="software_text" className="text-xs text-slate-500">
            Software 列表（每行一项，可为名称、版本或 URL）
          </Label>
          <Textarea
            id="software_text"
            value={String(formData.software_text ?? "")}
            onChange={(event) => updateForm("software_text", event.target.value)}
            placeholder={"GATK 4.5\nhttps://github.com/genotyping/QC"}
            rows={4}
          />
          <p className="text-xs text-slate-500">若填写 URL，请使用 http(s) 格式。</p>
        </div>
      )}
    />
  );
}
