import { useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  Button,
  Input,
  Label,
  formatIsoToDdMmYyyy,
  normalizeDdMmYyyyInput,
  parseDdMmYyyy,
} from "@ump/shared";
import type { ApplicationItem } from "@/data/mockApplications";

type Mode = "create" | "edit";

function ddMmYyyyToSubmittedIso(s: string): string {
  const d = parseDdMmYyyy(s.trim());
  if (!d) return new Date().toISOString();
  d.setHours(12, 0, 0, 0);
  return d.toISOString();
}

export interface ApplicantHistoryCrudDialogProps {
  open: boolean;
  mode: Mode;
  initialItem?: ApplicationItem;
  submitting: boolean;
  onOpenChange: (open: boolean) => void;
  onSubmit: (payload: { name: string; submittedDate: string }) => void;
}

export function ApplicantHistoryCrudDialog({
  open,
  mode,
  initialItem,
  submitting,
  onOpenChange,
  onSubmit,
}: ApplicantHistoryCrudDialogProps) {
  const [name, setName] = useState("");
  const [dateInput, setDateInput] = useState("");

  useEffect(() => {
    if (!open) return;
    if (mode === "edit" && initialItem) {
      setName(initialItem.name ?? "");
      setDateInput(formatIsoToDdMmYyyy(initialItem.submittedDate));
    } else {
      setName("");
      setDateInput(formatIsoToDdMmYyyy(new Date().toISOString()));
    }
  }, [open, mode, initialItem]);

  const title = mode === "create" ? "Đăng ký hồ sơ mới" : "Cập nhật thông tin hồ sơ";

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 py-2">
          <div className="space-y-2">
            <Label htmlFor="app-crud-name">Tên sáng kiến</Label>
            <Input
              id="app-crud-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Tên sáng kiến"
              disabled={submitting}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="app-crud-date">Ngày nộp</Label>
            <Input
              id="app-crud-date"
              type="text"
              inputMode="numeric"
              placeholder="dd/mm/yyyy"
              maxLength={10}
              value={dateInput}
              onChange={(e) => setDateInput(normalizeDdMmYyyyInput(e.target.value))}
              disabled={submitting}
            />
          </div>
        </div>
        <DialogFooter>
          <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
            Hủy
          </Button>
          <Button
            type="button"
            onClick={() => onSubmit({ name, submittedDate: ddMmYyyyToSubmittedIso(dateInput) })}
            disabled={submitting || !name.trim()}
          >
            {submitting ? "Đang lưu…" : mode === "create" ? "Tạo hồ sơ" : "Cập nhật"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
