import { Icon } from "@iconify/react";
import {
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogContent,
  IconButton,
  TextField,
  Typography,
} from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { validarPinSupervisor } from "../../../../api/pos-security.service";

const OPERACION_LABELS = {
  apertura_caja: "Apertura de Caja",
  cierre_caja: "Cierre de Caja",
  anulacion: "Anulación",
  descuento: "Descuento",
  retiro_caja: "Retiro de Caja",
  ingreso_caja: "Ingreso a Caja",
  nota_credito: "Nota de Crédito",
  cambio_precio: "Cambio de Precio",
  venta_credito: "Venta a Crédito",
  arqueo_diferencia: "Arqueo con Diferencia",
  cancelar_cierre: "Cancelar Cierre",
};

export function ModalPinSupervisor({
  open,
  onClose,
  onSuccess,
  tipoOperacion,
  contexto = {},
  titulo,
}) {
  const [username, setUsername] = useState("");
  const [pin, setPin] = useState("");
  const pinRef = useRef(null);

  const mutation = useMutation({
    mutationFn: () =>
      validarPinSupervisor({
        usuario_id_or_username: username,
        pin,
        tipo_operacion: tipoOperacion,
        contexto,
      }),
    onSuccess: (data) => {
      toast.success(`Autorizado por ${data.supervisor?.username || "supervisor"}`);
      onSuccess?.(data);
      handleClose();
    },
    onError: (error) => {
      const msg = error.response?.data?.message || "Error al validar PIN";
      toast.error(msg);
      setPin("");
      pinRef.current?.focus();
    },
  });

  const handleClose = useCallback(() => {
    setUsername("");
    setPin("");
    onClose?.();
  }, [onClose]);

  const handleSubmit = (e) => {
    e?.preventDefault();
    if (!username.trim()) {
      toast.error("Ingrese el usuario supervisor");
      return;
    }
    if (!pin || pin.length < 4) {
      toast.error("Ingrese un PIN de al menos 4 dígitos");
      return;
    }
    mutation.mutate();
  };

  useEffect(() => {
    if (open) {
      setUsername("");
      setPin("");
    }
  }, [open]);

  const handlePinChange = (e) => {
    const value = e.target.value.replace(/\D/g, "").slice(0, 6);
    setPin(value);
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="xs"
      fullWidth
      PaperProps={{
        sx: {
          borderRadius: 3,
          overflow: "hidden",
        },
      }}
    >
      <Box
        sx={{
          background: "linear-gradient(135deg, #f88533 0%, #ff6b6b 100%)",
          p: 3,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        }}
      >
        <Box sx={{ display: "flex", alignItems: "center", gap: 1.5 }}>
          <Icon icon="lucide:shield-check" width={28} color="white" />
          <Typography variant="h6" fontWeight={700} color="white">
            {titulo || "Autorización Supervisor"}
          </Typography>
        </Box>
        <IconButton onClick={handleClose} sx={{ color: "white" }}>
          <Icon icon="lucide:x" width={20} />
        </IconButton>
      </Box>

      <DialogContent sx={{ p: 3 }}>
        <Box
          sx={{
            mb: 3,
            p: 2,
            borderRadius: 2,
            bgcolor: "#fff3e0",
            display: "flex",
            alignItems: "center",
            gap: 1.5,
          }}
        >
          <Icon icon="lucide:lock-keyhole" width={20} color="#f88533" />
          <Typography variant="body2" color="text.secondary">
            Se requiere autorización para:{" "}
            <strong>
              {OPERACION_LABELS[tipoOperacion] || tipoOperacion}
            </strong>
          </Typography>
        </Box>

        <form onSubmit={handleSubmit}>
          <TextField
            label="Usuario supervisor"
            fullWidth
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            placeholder="Ej: admin"
            autoFocus
            sx={{ mb: 2.5 }}
            InputProps={{
              startAdornment: (
                <Icon
                  icon="lucide:user"
                  width={18}
                  color="#999"
                  style={{ marginRight: 8 }}
                />
              ),
            }}
          />

          <TextField
            label="PIN Supervisor"
            fullWidth
            type="password"
            value={pin}
            onChange={handlePinChange}
            placeholder="••••"
            inputRef={pinRef}
            inputProps={{ maxLength: 6, inputMode: "numeric" }}
            sx={{ mb: 3 }}
            InputProps={{
              startAdornment: (
                <Icon
                  icon="lucide:key-round"
                  width={18}
                  color="#999"
                  style={{ marginRight: 8 }}
                />
              ),
            }}
            onKeyDown={(e) => {
              if (e.key === "Enter" && pin.length >= 4 && username) {
                handleSubmit(e);
              }
            }}
          />

          <Box sx={{ display: "flex", gap: 2 }}>
            <Button
              variant="outlined"
              fullWidth
              onClick={handleClose}
              disabled={mutation.isPending}
              sx={{ py: 1.2 }}
            >
              Cancelar
            </Button>
            <Button
              variant="contained"
              fullWidth
              onClick={handleSubmit}
              disabled={mutation.isPending || !username || pin.length < 4}
              sx={{
                py: 1.2,
                background:
                  "linear-gradient(135deg, #f88533 0%, #ff6b6b 100%)",
                "&:hover": {
                  background:
                    "linear-gradient(135deg, #e07429 0%, #e55a5a 100%)",
                },
              }}
              startIcon={
                mutation.isPending ? (
                  <CircularProgress size={18} color="inherit" />
                ) : (
                  <Icon icon="lucide:shield-check" width={18} />
                )
              }
            >
              {mutation.isPending ? "Validando..." : "Autorizar"}
            </Button>
          </Box>
        </form>
      </DialogContent>
    </Dialog>
  );
}
