"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Layers, Save } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import {
  fetchSeedLotDetail,
  fetchSeedLotOptions,
  mapContentMixtureToForm,
  updateSeedLotContentMixture,
} from "../api";
import { ContentMixtureEditor } from "./ContentMixtureEditor";
import { NONE_SELECT_VALUE, type ContentMixtureRow, type SelectOption } from "../types";

interface SeedLotContentMixturePanelProps {
  seedLotDbId: string;
}

export function SeedLotContentMixturePanel({ seedLotDbId }: SeedLotContentMixturePanelProps) {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [rows, setRows] = useState<ContentMixtureRow[]>([]);
  const [germplasmOptions, setGermplasmOptions] = useState<SelectOption[]>([]);
  const [crossOptions, setCrossOptions] = useState<SelectOption[]>([]);
  const savingRef = useRef(false);

  const loadPanel = useCallback(async () => {
    const [detail, options] = await Promise.all([
      fetchSeedLotDetail(seedLotDbId),
      fetchSeedLotOptions(),
    ]);
    setRows(mapContentMixtureToForm(detail.content_mixture ?? detail.contentMixture));
    setGermplasmOptions(options.germplasms);
    setCrossOptions(options.crosses);
  }, [seedLotDbId]);

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    setError(null);
    loadPanel()
      .catch((event) => {
        if (!mounted) return;
        setError(event instanceof Error ? event.message : "加载批次组成失败");
      })
      .finally(() => {
        if (mounted) setLoading(false);
      });
    return () => { mounted = false; };
  }, [loadPanel]);

  const totalPercentage = useMemo(
    () => rows.reduce((sum, row) => {
      const value = Number(row.mixture_percentage);
      return sum + (Number.isNaN(value) ? 0 : value);
    }, 0),
    [rows],
  );

  const handleSave = async () => {
    if (savingRef.current) return;
    savingRef.current = true;
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      await updateSeedLotContentMixture(seedLotDbId, rows);
      setSuccess("批次组成已保存");
    } catch (event) {
      setError(event instanceof Error ? event.message : "保存失败");
    } finally {
      savingRef.current = false;
      setSaving(false);
    }
  };

  if (loading) {
    return <Skeleton className="h-64 w-full rounded-xl" />;
  }

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-base">
            <Layers className="h-5 w-5 text-emerald-500" />
            Content Mixture 批次组成
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-sm text-slate-600 dark:text-slate-300">
            维护 `seed_lot_content_mixture`：每行需指定 germplasm 或 cross 来源，占比合计建议为 100%。
          </p>

          <div className="space-y-2">
            <div className="flex items-center justify-between text-xs text-slate-500">
              <span>占比进度</span>
              <span className={Math.abs(totalPercentage - 100) <= 0.01 ? "text-emerald-600" : "text-amber-600"}>
                {totalPercentage}% / 100%
              </span>
            </div>
            <div className="h-2 overflow-hidden rounded-full bg-slate-100 dark:bg-slate-800">
              <div
                className={`h-full transition-all ${Math.abs(totalPercentage - 100) <= 0.01 ? "bg-emerald-500" : "bg-amber-500"}`}
                style={{ width: `${Math.min(totalPercentage, 100)}%` }}
              />
            </div>
          </div>

          <ContentMixtureEditor
            rows={rows}
            germplasmOptions={germplasmOptions}
            crossOptions={crossOptions}
            onChange={setRows}
          />

          {error ? (
            <p className="text-sm text-destructive">{error}</p>
          ) : null}
          {success ? (
            <p className="text-sm text-emerald-600 dark:text-emerald-400">{success}</p>
          ) : null}

          <div className="flex flex-wrap gap-2">
            <Button type="button" className="gap-2" disabled={saving} onClick={handleSave}>
              <Save className="h-4 w-4" />
              {saving ? "保存中…" : "保存组成"}
            </Button>
          </div>
        </CardContent>
      </Card>

      <p className="text-xs text-slate-500">
        组成中的 germplasm 可跳转至
        {" "}
        <Link href="/germplasm/germplasm" className="text-teal-600 hover:underline dark:text-teal-400">种质详情</Link>
        ；cross 可跳转至
        {" "}
        <Link href="/germplasm/cross-pedigree?tab=crosses" className="text-teal-600 hover:underline dark:text-teal-400">杂交列表</Link>
        。
      </p>
    </div>
  );
}
