"use client";

import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { putAdminUpdateDraw } from "@/api/admin-draws";
import { AdminDateTimeField } from "@/components/admin/admin-datetime-field";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  adminLocalScheduleValueToTimezoneNaive,
  getAdminBrowserTimeZoneLabel,
  isoToAdminLocalScheduleValue,
} from "@/lib/admin-datetime";
import { LOTTERY_SCHEDULE_TIMEZONE } from "@/lib/lottery-schedule-timezone";
import { LotteryApiBizError } from "@/types/api/errors";
import type { AdminDrawListItem } from "@/types/api/admin-draws";

type DrawEditDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  draw: AdminDrawListItem | null;
  scheduleTimezone?: string;
  onSaved: () => void | Promise<void>;
};

export function DrawEditDialog({
  open,
  onOpenChange,
  draw,
  scheduleTimezone,
  onSaved,
}: DrawEditDialogProps) {
  const { t } = useTranslation(["draws", "common"]);
  const [drawTime, setDrawTime] = useState("");
  const [closeTime, setCloseTime] = useState("");
  const [startTime, setStartTime] = useState("");
  const [drawNo, setDrawNo] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    queueMicrotask(() => {
      if (!open || draw == null) {
        return;
      }
      setDrawTime(isoToAdminLocalScheduleValue(draw.draw_time));
      setCloseTime(isoToAdminLocalScheduleValue(draw.close_time));
      setStartTime(isoToAdminLocalScheduleValue(draw.start_time));
      setDrawNo(draw.draw_no);
    });
  }, [open, draw]);

  async function submit(): Promise<void> {
    if (draw == null) {
      return;
    }
    if (!drawTime.trim()) {
      toast.error(t("createDraw.drawTimeRequired"));
      return;
    }
    setSaving(true);
    try {
      const scheduleTz = scheduleTimezone ?? LOTTERY_SCHEDULE_TIMEZONE;
      await putAdminUpdateDraw(draw.id, {
        draw_time: adminLocalScheduleValueToTimezoneNaive(drawTime.trim(), scheduleTz),
        close_time: closeTime.trim()
          ? adminLocalScheduleValueToTimezoneNaive(closeTime.trim(), scheduleTz)
          : undefined,
        start_time: startTime.trim()
          ? adminLocalScheduleValueToTimezoneNaive(startTime.trim(), scheduleTz)
          : undefined,
        draw_no: drawNo.trim() || undefined,
      });
      toast.success(t("editDraw.success"));
      onOpenChange(false);
      await onSaved();
    } catch (e) {
      toast.error(e instanceof LotteryApiBizError ? e.message : t("editDraw.failed"));
    } finally {
      setSaving(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent showCloseButton className="max-w-lg gap-4">
        <DialogHeader>
          <DialogTitle>{t("editDraw.title")}</DialogTitle>
          <DialogDescription>
            {t("editDraw.description", {
              tz: getAdminBrowserTimeZoneLabel(),
              drawNo: draw?.draw_no ?? "",
            })}
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-3">
          <AdminDateTimeField
            id="draw-edit-draw-time"
            label={t("drawTime")}
            value={drawTime}
            onChange={setDrawTime}
            required
          />
          <AdminDateTimeField
            id="draw-edit-close-time"
            label={t("closeTime")}
            value={closeTime}
            onChange={setCloseTime}
            optional
          />
          <AdminDateTimeField
            id="draw-edit-start-time"
            label={t("startTime")}
            value={startTime}
            onChange={setStartTime}
            optional
          />
          <div className="grid gap-1.5">
            <Label htmlFor="draw-edit-draw-no">{t("drawNo")}</Label>
            <Input
              id="draw-edit-draw-no"
              value={drawNo}
              placeholder={t("editDraw.drawNoPlaceholder")}
              onChange={(e) => setDrawNo(e.target.value)}
            />
          </div>
          <p className="text-xs text-muted-foreground">{t("createDraw.hint")}</p>
        </div>

        <DialogFooter className="gap-2 sm:gap-0">
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
            {t("actions.cancel", { ns: "common" })}
          </Button>
          <Button type="button" disabled={saving || draw == null} onClick={() => void submit()}>
            {saving ? t("editDraw.saving") : t("editDraw.submit")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
