"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Flower2, Pencil, Plus, Trash2 } from "lucide-react";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
} from "@/components/common/shadcn-enhanced";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
  sortPollinationEvents,
  updateCrossPollinationEvents,
} from "../api";
import type { CrossPollinationEventRecord } from "../types";

interface CrossPollinationEventPanelProps {
  crossId: string;
  crossName: string | null;
  events: CrossPollinationEventRecord[];
  onChanged?: () => void;
}

const SUCCESS_OPTIONS = [
  { value: "unknown", label: "未指定" },
  { value: "true", label: "成功" },
  { value: "false", label: "失败" },
];

const emptyForm = () => ({
  pollination_number: "",
  pollination_successful: "unknown",
  pollination_time_stamp: "",
});

const toLocalDateTime = (value: string | null) => {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value.slice(0, 16);
  const offset = date.getTimezoneOffset();
  const local = new Date(date.getTime() - offset * 60_000);
  return local.toISOString().slice(0, 16);
};

const fromLocalDateTime = (value: string) => {
  const normalized = value.trim();
  if (!normalized) return null;
  const date = new Date(normalized);
  if (Number.isNaN(date.getTime())) throw new Error("请输入有效的授粉时间");
  return date.toISOString();
};

const buildEventId = (event: Omit<CrossPollinationEventRecord, "id">, index: number) => {
  const number = String(event.pollination_number ?? "").trim();
  return number ? `num:${number}` : `idx:${index}`;
};

export function CrossPollinationEventPanel({
  crossId,
  crossName,
  events,
  onChanged,
}: CrossPollinationEventPanelProps) {
  const [rows, setRows] = useState<CrossPollinationEventRecord[]>(() => sortPollinationEvents(events));
  const [dialogOpen, setDialogOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<CrossPollinationEventRecord | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const savingRef = useRef(false);

  const sortedRows = useMemo(() => sortPollinationEvents(rows), [rows]);

  useEffect(() => {
    setRows(sortPollinationEvents(events));
  }, [events]);

  const persistEvents = useCallback(async (nextEvents: CrossPollinationEventRecord[]) => {
    if (savingRef.current) return;
    savingRef.current = true;
    setSaving(true);
    setError(null);
    try {
      const saved = await updateCrossPollinationEvents(crossId, nextEvents);
      setRows(sortPollinationEvents(saved.pollination_events));
      onChanged?.();
    } catch (event) {
      setError(event instanceof Error ? event.message : "保存失败");
      throw event;
    } finally {
      savingRef.current = false;
      setSaving(false);
    }
  }, [crossId, onChanged]);

  const openCreate = () => {
    setEditingId(null);
    setForm(emptyForm());
    setDialogOpen(true);
  };

  const openEdit = (row: CrossPollinationEventRecord) => {
    setEditingId(row.id);
    setForm({
      pollination_number: row.pollination_number ?? "",
      pollination_successful: row.pollination_successful === null
        ? "unknown"
        : String(row.pollination_successful),
      pollination_time_stamp: toLocalDateTime(row.pollination_time_stamp),
    });
    setDialogOpen(true);
  };

  const handleSave = async () => {
    const nextEvent = {
      pollination_number: form.pollination_number.trim() || null,
      pollination_successful: form.pollination_successful === "unknown"
        ? null
        : form.pollination_successful === "true",
      pollination_time_stamp: fromLocalDateTime(form.pollination_time_stamp),
    };

    const withoutCurrent = editingId
      ? rows.filter((row) => row.id !== editingId)
      : rows;

    const duplicateNumber = nextEvent.pollination_number
      && withoutCurrent.some((row) => row.pollination_number === nextEvent.pollination_number);
    if (duplicateNumber) {
      setError("同一 Cross 下授粉编号不能重复");
      return;
    }

    const nextRows = [
      ...withoutCurrent,
      {
        id: buildEventId(nextEvent, withoutCurrent.length),
        ...nextEvent,
      },
    ];

    try {
      await persistEvents(nextRows);
      setDialogOpen(false);
    } catch {
      // error already set
    }
  };

  const handleDelete = async () => {
    if (!deleteTarget) return;
    const nextRows = rows.filter((row) => row.id !== deleteTarget.id);
    try {
      await persistEvents(nextRows);
      setDeleteTarget(null);
    } catch {
      // error already set
    }
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between pb-3">
        <CardTitle className="flex items-center gap-2 text-base">
          <Flower2 className="h-4 w-4 text-pink-500" />
          授粉事件 (cross_pollination_event)
        </CardTitle>
        <Button size="sm" className="gap-1" onClick={openCreate} disabled={saving}>
          <Plus className="h-4 w-4" />
          新增授粉
        </Button>
      </CardHeader>
      <CardContent className="space-y-3">
        <p className="text-sm text-slate-500 dark:text-slate-400">
          {crossName || crossId}：按授粉时间倒序展示；删除授粉事件不会删除 Cross 主数据。
        </p>

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

        <Table>
          <TableHeader>
            <TableRow className="bg-slate-50 dark:bg-slate-900">
              <TableHead>授粉编号</TableHead>
              <TableHead>授粉时间</TableHead>
              <TableHead>是否成功</TableHead>
              <TableHead className="w-28 text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedRows.length === 0 ? (
              <TableRow>
                <TableCell colSpan={4} className="py-8 text-center text-sm text-slate-400">
                  暂无授粉事件
                </TableCell>
              </TableRow>
            ) : (
              sortedRows.map((row) => (
                <TableRow key={row.id}>
                  <TableCell>{row.pollination_number || "—"}</TableCell>
                  <TableCell>{row.pollination_time_stamp || "—"}</TableCell>
                  <TableCell>
                    {row.pollination_successful === null ? (
                      "—"
                    ) : (
                      <Badge variant={row.pollination_successful ? "default" : "secondary"}>
                        {row.pollination_successful ? "成功" : "失败"}
                      </Badge>
                    )}
                  </TableCell>
                  <TableCell className="text-right">
                    <div className="flex justify-end gap-1">
                      <Button size="sm" variant="outline" className="gap-1" onClick={() => openEdit(row)} disabled={saving}>
                        <Pencil className="h-3.5 w-3.5" />
                        编辑
                      </Button>
                      <Button size="sm" variant="outline" className="gap-1 text-destructive" onClick={() => setDeleteTarget(row)} disabled={saving}>
                        <Trash2 className="h-3.5 w-3.5" />
                        删除
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>

        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogContent className="max-w-lg" title={editingId ? "编辑授粉事件" : "新增授粉事件"}>
            <DialogBody className="space-y-4">
              <div>
                <Label className="mb-1.5 block text-sm">授粉编号</Label>
                <Input
                  value={form.pollination_number}
                  onChange={(event) => setForm((current) => ({ ...current, pollination_number: event.target.value }))}
                  placeholder="同一 Cross 下建议唯一"
                />
              </div>
              <div>
                <Label className="mb-1.5 block text-sm">授粉时间</Label>
                <Input
                  type="datetime-local"
                  value={form.pollination_time_stamp}
                  onChange={(event) => setForm((current) => ({ ...current, pollination_time_stamp: event.target.value }))}
                />
              </div>
              <div>
                <Label className="mb-1.5 block text-sm">是否授粉成功</Label>
                <Select
                  value={form.pollination_successful}
                  onValueChange={(value) => setForm((current) => ({ ...current, pollination_successful: value }))}
                >
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent position="popper" className="z-[110]">
                    {SUCCESS_OPTIONS.map((option) => (
                      <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </DialogBody>
            <DialogFooter>
              <Button variant="outline" onClick={() => setDialogOpen(false)} disabled={saving}>取消</Button>
              <Button onClick={handleSave} disabled={saving}>{saving ? "保存中..." : "保存"}</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        <AlertDialog open={Boolean(deleteTarget)} onOpenChange={(open) => !open && setDeleteTarget(null)}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>删除授粉事件？</AlertDialogTitle>
              <AlertDialogDescription>
                将删除授粉编号「{deleteTarget?.pollination_number || "未命名"}」；Cross 主数据不会被删除。
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={saving}>取消</AlertDialogCancel>
              <AlertDialogAction onClick={handleDelete} disabled={saving}>确认删除</AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </CardContent>
    </Card>
  );
}
