"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  Dialog as EnhancedDialog,
  DialogBody,
  DialogContent as EnhancedDialogContent,
  DialogFooter as EnhancedDialogFooter,
} from "@/components/common/shadcn-enhanced";
import { DateTimePicker } from "@/components/common/shadcn-enhanced/date-time-picker";
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 { createSeedLotTransaction } from "../api";
import {
  NONE_SELECT_VALUE,
  TRANSACTION_ACTION_LABEL,
  type SeedLotRecord,
  type SelectOption,
  type TransactionActionType,
} from "../types";

interface TransactionActionDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  seedLotOptions: SelectOption[];
  seedLotMap: Map<string, SeedLotRecord>;
  defaultSeedLotId?: string;
  onSuccess: () => void;
}

const actionOptions: TransactionActionType[] = ["in", "out", "transfer", "split", "consume"];

function parseDateTimeValue(value: string): Date | null {
  if (!value) return null;
  const parsed = new Date(value);
  return Number.isNaN(parsed.getTime()) ? null : parsed;
}

function formatDateTimeValue(date: Date | null): string {
  if (!date) return "";
  return date.toISOString();
}

export function TransactionActionDialog({
  open,
  onOpenChange,
  seedLotOptions,
  seedLotMap,
  defaultSeedLotId,
  onSuccess,
}: TransactionActionDialogProps) {
  const [action, setAction] = useState<TransactionActionType>("in");
  const [fromSeedLotId, setFromSeedLotId] = useState(NONE_SELECT_VALUE);
  const [toSeedLotId, setToSeedLotId] = useState(NONE_SELECT_VALUE);
  const [amount, setAmount] = useState("");
  const [units, setUnits] = useState("");
  const [description, setDescription] = useState("");
  const [timestamp, setTimestamp] = useState(new Date().toISOString());
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const savingRef = useRef(false);

  const resetForm = useCallback(() => {
    setAction("in");
    setFromSeedLotId(NONE_SELECT_VALUE);
    setToSeedLotId(defaultSeedLotId && defaultSeedLotId !== NONE_SELECT_VALUE ? defaultSeedLotId : NONE_SELECT_VALUE);
    setAmount("");
    setUnits("");
    setDescription("");
    setTimestamp(new Date().toISOString());
    setError(null);
  }, [defaultSeedLotId]);

  useEffect(() => {
    if (open) resetForm();
  }, [open, resetForm]);

  const relatedLot = useMemo(() => {
    const lotId = action === "in" ? toSeedLotId : fromSeedLotId;
    if (!lotId || lotId === NONE_SELECT_VALUE) return null;
    return seedLotMap.get(lotId) ?? null;
  }, [action, fromSeedLotId, seedLotMap, toSeedLotId]);

  useEffect(() => {
    if (relatedLot?.units) {
      setUnits(relatedLot.units);
    }
  }, [relatedLot]);

  const requiresFrom = action === "out" || action === "transfer" || action === "split" || action === "consume";
  const requiresTo = action === "in" || action === "transfer" || action === "split";
  const requiresDescription = action === "out" || action === "consume";

  const handleSubmit = async () => {
    if (savingRef.current) return;
    savingRef.current = true;
    setSaving(true);
    setError(null);
    try {
      await createSeedLotTransaction(
        {
          action,
          amount,
          description,
          timestamp,
          units,
          from_seed_lot_id: fromSeedLotId,
          to_seed_lot_id: toSeedLotId,
        },
        seedLotMap,
      );
      onSuccess();
      onOpenChange(false);
    } catch (event) {
      setError(event instanceof Error ? event.message : "创建交易失败");
    } finally {
      savingRef.current = false;
      setSaving(false);
    }
  };

  return (
    <EnhancedDialog open={open} onOpenChange={onOpenChange}>
      <EnhancedDialogContent title="新建库存交易" defaultWidth={720} defaultHeight={640} minHeight={520}>
        <DialogBody className="space-y-4">
          <p className="text-sm text-muted-foreground">
            库存数量应通过入库、出库、转移、分装、消耗等业务动作更新，不建议直接修改批次 amount。
          </p>

          {error ? (
            <div className="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 className="mb-1.5 block text-sm">业务动作</Label>
              <Select value={action} onValueChange={(value) => setAction(value as TransactionActionType)}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent position="popper" className="z-[110]">
                  {actionOptions.map((option) => (
                    <SelectItem key={option} value={option}>{TRANSACTION_ACTION_LABEL[option]}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {requiresFrom ? (
              <div>
                <Label className="mb-1.5 block text-sm">来源批次</Label>
                <Select value={fromSeedLotId} onValueChange={setFromSeedLotId}>
                  <SelectTrigger><SelectValue placeholder="选择来源批次" /></SelectTrigger>
                  <SelectContent position="popper" className="z-[110] max-h-60">
                    <SelectItem value={NONE_SELECT_VALUE}>请选择</SelectItem>
                    {seedLotOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {relatedLot && requiresFrom ? (
                  <p className="mt-1 text-xs text-slate-500">当前库存：{relatedLot.amount ?? 0} {relatedLot.units ?? ""}</p>
                ) : null}
              </div>
            ) : null}

            {requiresTo ? (
              <div>
                <Label className="mb-1.5 block text-sm">目标批次</Label>
                <Select value={toSeedLotId} onValueChange={setToSeedLotId}>
                  <SelectTrigger><SelectValue placeholder="选择目标批次" /></SelectTrigger>
                  <SelectContent position="popper" className="z-[110] max-h-60">
                    <SelectItem value={NONE_SELECT_VALUE}>请选择</SelectItem>
                    {seedLotOptions.map((option) => (
                      <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            ) : null}

            <div>
              <Label className="mb-1.5 block text-sm">流转数量<span className="ml-0.5 text-red-500">*</span></Label>
              <Input type="number" min={0} value={amount} onChange={(event) => setAmount(event.target.value)} placeholder="大于 0" />
            </div>

            <div>
              <Label className="mb-1.5 block text-sm">单位<span className="ml-0.5 text-red-500">*</span></Label>
              <Input value={units} onChange={(event) => setUnits(event.target.value)} placeholder="继承批次单位" />
            </div>

            <div className="md:col-span-2">
              <Label className="mb-1.5 block text-sm">流转时间</Label>
              <DateTimePicker
                mode="datetime-minute"
                value={parseDateTimeValue(timestamp)}
                onChange={(date) => setTimestamp(formatDateTimeValue(date))}
                className="w-full"
              />
            </div>

            <div className="md:col-span-2">
              <Label className="mb-1.5 block text-sm">
                流转说明
                {requiresDescription ? <span className="ml-0.5 text-red-500">*</span> : null}
              </Label>
              <Textarea
                value={description}
                onChange={(event) => setDescription(event.target.value)}
                placeholder={action === "consume" ? "请填写消耗或报废原因" : "如用于某 study、分装原因等"}
                rows={3}
                className="resize-none"
              />
            </div>
          </div>
        </DialogBody>
        <EnhancedDialogFooter className="flex justify-end gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>取消</Button>
          <Button onClick={() => void handleSubmit()} disabled={saving}>{saving ? "提交中..." : "提交交易"}</Button>
        </EnhancedDialogFooter>
      </EnhancedDialogContent>
    </EnhancedDialog>
  );
}
