"use client";

import { InventoryLotLineResult, InventoryResult } from "@/app/api/inventory";
import { handleBadItem } from "@/app/api/stockIssue/actions";
import { msg, msgError } from "@/components/Swal/CustomAlerts";
import {
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Typography,
} from "@mui/material";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";

interface Props {
  open: boolean;
  onClose: () => void;
  lotLine: InventoryLotLineResult | null;
  inventory: InventoryResult | null;
  currentUserId?: number;
  onSuccess: (payload: {
    inventoryLotLineId: number;
    qty: number;
  }) => void | Promise<void>;
}

const BadItemHandleModal: React.FC<Props> = ({
  open,
  onClose,
  lotLine,
  inventory,
  currentUserId,
  onSuccess,
}) => {
  const { t } = useTranslation("stockIssue");
  const inFlightRef = useRef(false);
  const [qty, setQty] = useState("");
  const [remarks, setRemarks] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const maxQty = lotLine?.availableQty ?? 0;

  useEffect(() => {
    if (open && lotLine) {
      setQty(String(Math.max(0, Math.floor(maxQty))));
      setRemarks("");
    }
  }, [open, lotLine, maxQty]);

  const handleSubmit = useCallback(async () => {
    if (!lotLine || !currentUserId) return;
    if (inFlightRef.current) return;

    const parsed = parseInt(qty.replace(/\D/g, ""), 10);
    if (Number.isNaN(parsed) || parsed < 1) {
      msgError(t("Please enter a valid quantity"));
      return;
    }
    if (parsed > maxQty) {
      msgError(t("Quantity exceeds available quantity"));
      return;
    }

    inFlightRef.current = true;
    setSubmitting(true);
    try {
      const res = await handleBadItem({
        inventoryLotLineId: lotLine.id,
        qty: parsed,
        remarks: remarks.trim() || undefined,
        handler: currentUserId,
      });
      if (res?.code && res.code !== "SUCCESS") {
        throw new Error(res.message || t("Failed to submit"));
      }
      msg(t("Saved successfully"));
      onClose();
      await onSuccess({
        inventoryLotLineId: lotLine.id,
        qty: parsed,
      });
    } catch (e: unknown) {
      msgError(e instanceof Error ? e.message : t("Failed to submit"));
    } finally {
      setSubmitting(false);
      inFlightRef.current = false;
    }
  }, [lotLine, currentUserId, qty, remarks, maxQty, t, onClose, onSuccess]);

  if (!lotLine || !inventory) return null;

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>{t("Bad Item Handle")}</DialogTitle>
      <DialogContent>
        <Box sx={{ display: "flex", flexDirection: "column", gap: 1, mt: 1 }}>
          <Typography variant="body2">
            <strong>{t("Item Code")}:</strong> {inventory.itemCode}
          </Typography>
          <Typography variant="body2">
            <strong>{t("Item")}:</strong> {inventory.itemName}
          </Typography>
          <Typography variant="body2">
            <strong>{t("Lot No.")}:</strong> {lotLine.lotNo}
          </Typography>
          <Typography variant="body2">
            <strong>{t("Location")}:</strong> {lotLine.warehouse?.code ?? "—"}
          </Typography>
          <Typography variant="body2">
            <strong>{t("Available Qty")}:</strong> {maxQty} {lotLine.uom ?? ""}
          </Typography>
          <TextField
            label={t("Defective Qty")}
            fullWidth
            value={qty}
            onChange={(e) => {
              const raw = e.target.value.replace(/\D/g, "");
              if (raw === "") {
                setQty("");
                return;
              }
              const n = parseInt(raw, 10);
              if (!Number.isNaN(n)) {
                setQty(String(Math.min(Math.max(1, n), maxQty)));
              }
            }}
            sx={{ mt: 1 }}
          />
          <TextField
            label={t("Remarks")}
            fullWidth
            multiline
            minRows={2}
            value={remarks}
            onChange={(e) => setRemarks(e.target.value)}
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={submitting}>
          {t("Cancel")}
        </Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={submitting || !currentUserId || !qty}
        >
          {submitting ? t("Processing...") : t("Submit")}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default BadItemHandleModal;
