"use client";

import Link from "next/link";
import { useCallback, useMemo } from "react";
import { FileDown } from "lucide-react";
import { BrapiEntityPage, type BrapiFormField } from "@/components/brapi/BrapiEntityPage";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
  createVariantSetFormatRow,
  deleteVariantSetFormatRow,
  fetchVariantSetFormatRows,
  normalizeVariantSetFormatFormData,
  updateVariantSetFormatRow,
} from "../api";
import { DATA_FORMAT_OPTIONS, FILE_FORMAT_OPTIONS, NONE_SELECT_VALUE } from "../types";

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

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

const boolLabel = (value: unknown) => (value === true ? "是" : value === false ? "否" : "—");

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

  const findRowById = useCallback(async (id: string) => {
    const rows = await fetchVariantSetFormatRows(variantSetDbId);
    const row = rows.find((item) => item.id === id);
    if (!row) throw new Error("Available Format 不存在");
    return normalizeVariantSetFormatFormData(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: "Format ID", type: "text", placeholder: "留空则系统自动生成" },
    {
      key: "data_format",
      label: "数据格式 (data_format)",
      type: "select",
      required: true,
      options: optionOrNone("请选择数据格式", DATA_FORMAT_OPTIONS),
    },
    {
      key: "file_format",
      label: "文件格式 (file_format)",
      type: "select",
      required: true,
      options: optionOrNone("请选择 MIME 类型", FILE_FORMAT_OPTIONS),
    },
    { key: "fileurl", label: "文件 URL (fileurl)", type: "text", placeholder: "https://example.com/data.vcf" },
    { key: "sep_phased", label: "Phased 分隔符", type: "text", placeholder: "如 |" },
    { key: "sep_unphased", label: "Unphased 分隔符", type: "text", placeholder: "如 /" },
    { key: "unknown_string", label: "缺失值字符串", type: "text", placeholder: "如 NA 或 ." },
  ], []);

  const columns = useMemo(() => [
    { key: "dataFormat", label: "数据格式" },
    { key: "fileFormat", label: "MIME" },
    {
      key: "fileURL",
      label: "文件 URL",
      render: (value: unknown) => {
        const url = String(value ?? "").trim();
        if (!url) return "—";
        return (
          <Link href={url} target="_blank" rel="noopener noreferrer" className="break-all text-violet-600 hover:underline dark:text-violet-400">
            {url}
          </Link>
        );
      },
    },
    {
      key: "expandHomozygotes",
      label: "展开纯合",
      render: (value: unknown) => boolLabel(value),
    },
    { key: "sepPhased", label: "Phased 分隔符" },
    { key: "sepUnphased", label: "Unphased 分隔符" },
    { key: "unknownString", label: "缺失值" },
  ], []);

  return (
    <BrapiEntityPage
      useEnhancedDialog
      icon={FileDown}
      iconBg="bg-gradient-to-br from-sky-500 to-blue-600"
      title="Available Formats"
      description="配置 VariantSet 可下载的数据格式与文件地址；矩阵格式可设置分隔符与缺失值字符串。"
      addLabel="新增 Format"
      columns={columns}
      fields={fields}
      data={[]}
      loadData={loadRows}
      fetchRecord={findRowById}
      createRecord={(payload) => wrapMutation(() => createVariantSetFormatRow(variantSetDbId, payload))() as Promise<Record<string, unknown>>}
      updateRecord={(id, payload) => wrapMutation(() => updateVariantSetFormatRow(variantSetDbId, id, payload))() as Promise<Record<string, unknown>>}
      deleteRecord={(id) => wrapMutation(() => deleteVariantSetFormatRow(variantSetDbId, id))().then(() => undefined)}
      renderFormExtra={({ formData, updateFormBatch }) => (
        <div className="col-span-2 flex items-center justify-between rounded-lg border border-sky-100 bg-sky-50/60 p-3 dark:border-sky-900/40 dark:bg-sky-950/30">
          <div>
            <Label htmlFor="expand_homozygotes" className="text-sm font-medium text-sky-900 dark:text-sky-100">
              展开纯合位点 (expand_homozygotes)
            </Label>
            <p className="mt-1 text-xs text-sky-800/80 dark:text-sky-200/80">
              矩阵格式导入时会按此设置解析 phased / unphased 与缺失值。
            </p>
          </div>
          <Switch
            id="expand_homozygotes"
            checked={formData.expand_homozygotes === true}
            onCheckedChange={(checked) => updateFormBatch({ expand_homozygotes: checked })}
          />
        </div>
      )}
    />
  );
}
