"use client";

import { Plus, Trash2 } from "lucide-react";
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 { NONE_SELECT_VALUE, type ContentMixtureRow, type SelectOption } from "../types";

interface ContentMixtureEditorProps {
  rows: ContentMixtureRow[];
  germplasmOptions: SelectOption[];
  crossOptions: SelectOption[];
  onChange: (rows: ContentMixtureRow[]) => void;
  disabled?: boolean;
}

const emptyRow = (): ContentMixtureRow => ({
  germplasm_id: NONE_SELECT_VALUE,
  cross_id: NONE_SELECT_VALUE,
  mixture_percentage: "",
});

export function ContentMixtureEditor({
  rows,
  germplasmOptions,
  crossOptions,
  onChange,
  disabled = false,
}: ContentMixtureEditorProps) {
  const totalPercentage = rows.reduce((sum, row) => {
    const value = Number(row.mixture_percentage);
    return sum + (Number.isNaN(value) ? 0 : value);
  }, 0);

  const updateRow = (index: number, patch: Partial<ContentMixtureRow>) => {
    onChange(rows.map((row, rowIndex) => (rowIndex === index ? { ...row, ...patch } : row)));
  };

  const addRow = () => {
    onChange([...rows, emptyRow()]);
  };

  const removeRow = (index: number) => {
    if (rows.length <= 1) return;
    onChange(rows.filter((_, rowIndex) => rowIndex !== index));
  };

  return (
    <div className="md:col-span-2 space-y-3 rounded-lg border border-slate-200 bg-slate-50/70 p-4 dark:border-slate-800 dark:bg-slate-900/40">
      <div className="flex items-start justify-between gap-3">
        <div>
          <Label className="text-sm font-medium text-slate-800 dark:text-slate-100">批次组成</Label>
          <p className="mt-1 text-xs text-slate-500 dark:text-slate-400">
            单一材料需一条 100% 记录；混合批次多条占比合计应为 100%。材料与杂交来源至少填一项。
          </p>
        </div>
        {!disabled ? (
          <Button type="button" variant="outline" size="sm" className="shrink-0 gap-1" onClick={addRow}>
            <Plus className="h-3.5 w-3.5" />
            添加组成
          </Button>
        ) : null}
      </div>

      <div className="space-y-3">
        {rows.map((row, index) => (
          <div
            key={`mixture-${index}`}
            className="grid grid-cols-1 gap-3 rounded-md border border-slate-200 bg-white p-3 dark:border-slate-800 dark:bg-slate-950 md:grid-cols-[1fr_1fr_120px_auto]"
          >
            <div>
              <Label className="mb-1.5 block text-xs text-slate-500">来源材料</Label>
              <Select
                value={row.germplasm_id}
                onValueChange={(value) => updateRow(index, { germplasm_id: value })}
                disabled={disabled}
              >
                <SelectTrigger><SelectValue placeholder="选择 germplasm" /></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 text-slate-500">来源杂交</Label>
              <Select
                value={row.cross_id}
                onValueChange={(value) => updateRow(index, { cross_id: value })}
                disabled={disabled}
              >
                <SelectTrigger><SelectValue placeholder="选择 cross" /></SelectTrigger>
                <SelectContent position="popper" className="z-[110] max-h-60">
                  <SelectItem value={NONE_SELECT_VALUE}>不指定杂交</SelectItem>
                  {crossOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="mb-1.5 block text-xs text-slate-500">占比 (%)</Label>
              <Input
                type="number"
                min={0}
                max={100}
                value={row.mixture_percentage}
                onChange={(event) => updateRow(index, { mixture_percentage: event.target.value })}
                placeholder="100"
                disabled={disabled}
              />
            </div>
            {!disabled && rows.length > 1 ? (
              <div className="flex items-end">
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  className="text-slate-400 hover:text-red-500"
                  onClick={() => removeRow(index)}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            ) : null}
          </div>
        ))}
      </div>

      <p className={`text-xs ${Math.abs(totalPercentage - 100) <= 0.01 ? "text-emerald-600 dark:text-emerald-400" : "text-amber-600 dark:text-amber-400"}`}>
        当前占比合计：{totalPercentage}%
        {Math.abs(totalPercentage - 100) > 0.01 ? "（建议调整为 100%）" : ""}
      </p>
    </div>
  );
}
