"use client";

import { useEffect, useMemo, useState } from "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 { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
} from "@/components/common/shadcn-enhanced";
import { updateTrialRow } from "../api";
import { TrialContactsEditor } from "./TrialContactsEditor";
import { TrialPublicationsEditor } from "./TrialPublicationsEditor";
import { mapContactsFromApi, mapPublicationsFromApi } from "./trialRelationUtils";
import { NONE_SELECT_VALUE, type SelectOption, type TrialContactRow, type TrialPublicationRow, type TrialRecord } from "../types";

type TrialMetaDialogProps = {
  open: boolean;
  record: TrialRecord;
  cropOptions: SelectOption[];
  programOptions: SelectOption[];
  personOptions: SelectOption[];
  onOpenChange: (open: boolean) => void;
  onSaved: (record: TrialRecord) => void;
};

export function TrialMetaDialog({
  open,
  record,
  cropOptions,
  programOptions,
  personOptions,
  onOpenChange,
  onSaved,
}: TrialMetaDialogProps) {
  const [form, setForm] = useState({
    trial_name: "",
    trial_description: "",
    trialpui: "",
    documentationurl: "",
    start_date: "",
    end_date: "",
    active: "true",
    program_id: NONE_SELECT_VALUE,
    crop_id: NONE_SELECT_VALUE,
  });
  const [trialContacts, setTrialContacts] = useState<TrialContactRow[]>([]);
  const [trialPublications, setTrialPublications] = useState<TrialPublicationRow[]>([]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setForm({
      trial_name: record.trial_name || record.trialName || "",
      trial_description: record.trial_description || record.trialDescription || "",
      trialpui: record.trialpui || record.trialPUI || "",
      documentationurl: record.documentationurl || record.documentationURL || "",
      start_date: record.start_date || record.startDate || "",
      end_date: record.end_date || record.endDate || "",
      active: record.active === false ? "false" : "true",
      program_id: record.program_id || record.programDbId || NONE_SELECT_VALUE,
      crop_id: record.crop_id || record.cropDbId || NONE_SELECT_VALUE,
    });
    setTrialContacts(record.trialContacts ?? mapContactsFromApi(record.contacts));
    setTrialPublications(record.trialPublications ?? mapPublicationsFromApi(record.publications));
    setError(null);
  }, [open, record]);

  const programSelectOptions = useMemo(
    () => [{ value: NONE_SELECT_VALUE, label: "不关联项目" }, ...programOptions],
    [programOptions],
  );

  const cropSelectOptions = useMemo(
    () => [{ value: NONE_SELECT_VALUE, label: "不关联作物" }, ...cropOptions],
    [cropOptions],
  );

  const updateField = (key: keyof typeof form, value: string) => {
    setForm((current) => ({ ...current, [key]: value }));
  };

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    try {
      const updated = await updateTrialRow(record.trialDbId, {
        ...form,
        trialContacts,
        trialPublications,
      });
      onSaved(updated);
      onOpenChange(false);
    } catch (event) {
      setError(event instanceof Error ? event.message : "保存失败");
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent title="编辑试验" defaultWidth={960} defaultHeight={720} minHeight={520}>
        <DialogBody>
          {error ? (
            <div className="mb-3 rounded-lg border border-destructive/20 bg-destructive/10 px-3 py-2 text-sm text-destructive">
              {error}
            </div>
          ) : null}
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="md:col-span-2">
              <Label htmlFor="edit-trial-name" className="mb-1.5 block text-sm">
                试验名称<span className="ml-0.5 text-red-500">*</span>
              </Label>
              <Input
                id="edit-trial-name"
                value={form.trial_name}
                onChange={(event) => updateField("trial_name", event.target.value)}
              />
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">所属项目</Label>
              <Select value={form.program_id} onValueChange={(value) => updateField("program_id", value)}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent position="item-aligned">
                  {programSelectOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">作物</Label>
              <Select value={form.crop_id} onValueChange={(value) => updateField("crop_id", value)}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent position="item-aligned">
                  {cropSelectOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">状态</Label>
              <Select value={form.active} onValueChange={(value) => updateField("active", value)}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent position="item-aligned">
                  <SelectItem value="true">活跃</SelectItem>
                  <SelectItem value="false">停用</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">Trial PUI</Label>
              <Input value={form.trialpui} onChange={(event) => updateField("trialpui", event.target.value)} />
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">开始日期</Label>
              <Input type="date" value={form.start_date} onChange={(event) => updateField("start_date", event.target.value)} />
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">结束日期</Label>
              <Input type="date" value={form.end_date} onChange={(event) => updateField("end_date", event.target.value)} />
            </div>
            <div className="md:col-span-2">
              <Label className="mb-1.5 block text-sm">文档地址</Label>
              <Input
                value={form.documentationurl}
                onChange={(event) => updateField("documentationurl", event.target.value)}
                placeholder="https://..."
              />
            </div>
            <div className="md:col-span-2">
              <Label className="mb-1.5 block text-sm">试验说明</Label>
              <Textarea
                value={form.trial_description}
                onChange={(event) => updateField("trial_description", event.target.value)}
                rows={3}
                className="resize-none"
              />
            </div>
            <TrialContactsEditor
              contacts={trialContacts}
              personOptions={personOptions}
              onChange={setTrialContacts}
              disabled={saving}
            />
            <TrialPublicationsEditor
              publications={trialPublications}
              onChange={setTrialPublications}
              disabled={saving}
            />
          </div>
        </DialogBody>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>取消</Button>
          <Button onClick={handleSave} disabled={saving}>{saving ? "保存中..." : "保存"}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
