"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { PARENT_TYPE_OPTIONS, parentTypeLabel } from "../constants";
import {
  buildCrossParentFormState,
  fetchCrossPedigreeOptions,
  updateCrossParents,
} from "../api";
import { NONE_SELECT_VALUE, type CrossParentFormState, type SelectOption } from "../types";
import type { CrossParent } from "@/lib/api/types.gen";

interface CrossParentsPanelProps {
  crossId: string;
  planned: boolean;
  crossName: string | null;
  crossingProjectId: string | null;
  crossingProjectName: string | null;
  parent1: CrossParent | null;
  parent2: CrossParent | null;
  onChanged?: () => void;
}

function ParentSlotEditor({
  title,
  slot,
  parentType,
  germplasmId,
  observationUnitId,
  germplasmOptions,
  observationUnitOptions,
  onChange,
}: {
  title: string;
  slot: "parent1" | "parent2";
  parentType: string;
  germplasmId: string;
  observationUnitId: string;
  germplasmOptions: SelectOption[];
  observationUnitOptions: SelectOption[];
  onChange: (patch: Partial<CrossParentFormState>) => void;
}) {
  const prefix = slot;
  return (
    <div className="rounded-lg border border-slate-200 p-4 dark:border-slate-800">
      <h4 className="mb-3 text-sm font-medium text-slate-800 dark:text-slate-100">{title}</h4>
      <div className="grid gap-3 md:grid-cols-3">
        <div>
          <Label className="mb-1.5 block text-xs">parent_type</Label>
          <Select
            value={parentType || NONE_SELECT_VALUE}
            onValueChange={(value) => onChange({ [`${prefix}_type`]: value } as Partial<CrossParentFormState>)}
          >
            <SelectTrigger><SelectValue placeholder="选择亲本角色" /></SelectTrigger>
            <SelectContent position="popper" className="z-[110] max-h-60">
              <SelectItem value={NONE_SELECT_VALUE}>不指定</SelectItem>
              {PARENT_TYPE_OPTIONS.map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div>
          <Label className="mb-1.5 block text-xs">germplasm_id</Label>
          <Select
            value={germplasmId || NONE_SELECT_VALUE}
            onValueChange={(value) => onChange({ [`${prefix}_germplasm_id`]: value } as Partial<CrossParentFormState>)}
          >
            <SelectTrigger><SelectValue placeholder="选择种质" /></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>
        </div>
        <div>
          <Label className="mb-1.5 block text-xs">observation_unit_id</Label>
          <Select
            value={observationUnitId || NONE_SELECT_VALUE}
            onValueChange={(value) => onChange({ [`${prefix}_observation_unit_id`]: value } as Partial<CrossParentFormState>)}
          >
            <SelectTrigger><SelectValue placeholder="选择观测单元" /></SelectTrigger>
            <SelectContent position="popper" className="z-[110] max-h-60">
              <SelectItem value={NONE_SELECT_VALUE}>不指定观测单元</SelectItem>
              {observationUnitOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>
    </div>
  );
}

export function CrossParentsPanel({
  crossId,
  planned,
  crossName,
  crossingProjectId,
  crossingProjectName,
  parent1,
  parent2,
  onChanged,
}: CrossParentsPanelProps) {
  const [germplasmOptions, setGermplasmOptions] = useState<SelectOption[]>([]);
  const [observationUnitOptions, setObservationUnitOptions] = useState<SelectOption[]>([]);
  const [loadingOptions, setLoadingOptions] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const savingRef = useRef(false);
  const [form, setForm] = useState<CrossParentFormState>(() => buildCrossParentFormState(
    crossId,
    planned,
    crossingProjectId,
    crossingProjectName,
    parent1,
    parent2,
  ));

  useEffect(() => {
    setForm(buildCrossParentFormState(
      crossId,
      planned,
      crossingProjectId,
      crossingProjectName,
      parent1,
      parent2,
    ));
  }, [crossId, planned, crossingProjectId, crossingProjectName, parent1, parent2]);

  useEffect(() => {
    let mounted = true;
    setLoadingOptions(true);
    fetchCrossPedigreeOptions()
      .then((options) => {
        if (!mounted) return;
        setGermplasmOptions(options.germplasm);
        setObservationUnitOptions(options.observationUnits);
      })
      .finally(() => {
        if (mounted) setLoadingOptions(false);
      });
    return () => { mounted = false; };
  }, []);

  const handleSave = useCallback(async () => {
    if (savingRef.current) return;
    savingRef.current = true;
    setSaving(true);
    setError(null);
    try {
      await updateCrossParents(form);
      onChanged?.();
    } catch (event) {
      setError(event instanceof Error ? event.message : "保存失败");
    } finally {
      savingRef.current = false;
      setSaving(false);
    }
  }, [form, onChanged]);

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

  return (
    <Card>
      <CardHeader className="pb-3">
        <CardTitle className="flex items-center gap-2 text-base">
          <Users className="h-4 w-4 text-violet-500" />
          杂交亲本 (cross_parent)
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <p className="text-sm text-slate-500 dark:text-slate-400">
          {crossName || crossId}：维护 parent1 / parent2；germplasm 与 observation_unit 至少填写一项。
        </p>

        <div>
          <Label className="mb-1.5 block text-sm">crossing_project_id（只读）</Label>
          <Input readOnly value={crossingProjectName || crossingProjectId || "—"} />
        </div>

        <ParentSlotEditor
          title="Parent 1"
          slot="parent1"
          parentType={form.parent1_type}
          germplasmId={form.parent1_germplasm_id}
          observationUnitId={form.parent1_observation_unit_id}
          germplasmOptions={germplasmOptions}
          observationUnitOptions={observationUnitOptions}
          onChange={(patch) => setForm((current) => ({ ...current, ...patch }))}
        />
        <ParentSlotEditor
          title="Parent 2"
          slot="parent2"
          parentType={form.parent2_type}
          germplasmId={form.parent2_germplasm_id}
          observationUnitId={form.parent2_observation_unit_id}
          germplasmOptions={germplasmOptions}
          observationUnitOptions={observationUnitOptions}
          onChange={(patch) => setForm((current) => ({ ...current, ...patch }))}
        />

        <div className="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs text-slate-600 dark:border-slate-800 dark:bg-slate-900 dark:text-slate-300">
          当前摘要：
          Parent1 {parentTypeLabel(form.parent1_type)} /
          Parent2 {parentTypeLabel(form.parent2_type)}
        </div>

        {error ? <p className="text-sm text-red-500">{error}</p> : null}

        <div className="flex justify-end">
          <Button onClick={handleSave} disabled={saving}>
            {saving ? "保存中..." : "保存亲本"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
