import { CheckCircle, Security, Upload, Warning } from "@mui/icons-material";
import {
    Alert,
    Box,
    Button,
    Chip,
    Divider,
    Paper,
    TextField,
    Typography,
} from "@mui/material";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useRef, useState } from "react";
import { toast } from "sonner";
import api from "../../../api/api.config";
import { useEmpresa } from "../../../context/EmpresaContext";

export const CertificadoConfig = () => {
  const { empresa, empresaId, refetch } = useEmpresa();
  const queryClient = useQueryClient();
  const fileInputRef = useRef(null);

  const certificadoActual = empresa?.certificados?.[0];
  const hasCertificado = !!certificadoActual;

  const [pin, setPin] = useState("");
  const [file, setFile] = useState(null);

  const mutation = useMutation({
    mutationFn: async ({ file, pin }) => {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("pin", pin);
      const response = await api.post(
        `/empresas/${empresaId}/certificado`,
        formData,
        {
          headers: { "Content-Type": "multipart/form-data" },
        },
      );
      return response.data;
    },
    onSuccess: () => {
      toast.success("Certificado cargado correctamente");
      queryClient.invalidateQueries({ queryKey: ["empresa"] });
      refetch();
      setFile(null);
      setPin("");
    },
    onError: (error) => {
      toast.error(
        error.response?.data?.message || "Error al cargar certificado",
      );
    },
  });

  const handleFileChange = (e) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile) {
      if (
        !selectedFile.name.endsWith(".p12") &&
        !selectedFile.name.endsWith(".pfx")
      ) {
        toast.error("El archivo debe ser .p12 o .pfx");
        return;
      }
      setFile(selectedFile);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!file || !pin) {
      toast.error("Seleccione un archivo y ingrese el PIN");
      return;
    }
    mutation.mutate({ file, pin });
  };

  return (
    <Paper sx={{ p: { xs: 2, sm: 3 } }}>
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          mb: 1,
          gap: 1,
          flexWrap: "wrap",
        }}
      >
        <Typography
          variant="h6"
          sx={{
            display: "flex",
            alignItems: "center",
            gap: 1,
            fontSize: { xs: "1rem", sm: "1.25rem" },
          }}
        >
          <Security color="primary" />
          Certificado Digital
        </Typography>
        {hasCertificado ? (
          <Chip
            icon={<CheckCircle />}
            label="Configurado"
            color="success"
            size="small"
          />
        ) : (
          <Chip
            icon={<Warning />}
            label="Pendiente"
            color="warning"
            size="small"
          />
        )}
      </Box>
      <Typography
        variant="body2"
        color="text.secondary"
        sx={{ mb: 2, fontSize: { xs: "0.75rem", sm: "0.875rem" } }}
      >
        Certificado para firma electrónica de documentos
      </Typography>
      <Divider sx={{ mb: 3 }} />

      {hasCertificado && (
        <Alert severity="success" sx={{ mb: 3 }}>
          <Typography variant="subtitle2">Certificado activo</Typography>
          <Typography variant="body2">
            Titular: <strong>{certificadoActual.titular}</strong>
          </Typography>
          <Typography variant="body2">
            Emisor: {certificadoActual.emisor}
          </Typography>
          <Typography variant="body2">
            Vence:{" "}
            {new Date(certificadoActual.fecha_vencimiento).toLocaleDateString(
              "es-PY",
            )}
          </Typography>
        </Alert>
      )}

      <Box
        component="form"
        onSubmit={handleSubmit}
        sx={{ display: "flex", flexDirection: "column", gap: 2 }}
      >
        <input
          type="file"
          ref={fileInputRef}
          onChange={handleFileChange}
          accept=".p12,.pfx"
          style={{ display: "none" }}
        />

        <Box
          sx={{
            border: "2px dashed",
            borderColor: file ? "success.main" : "divider",
            borderRadius: 2,
            p: 3,
            textAlign: "center",
            cursor: "pointer",
            bgcolor: file ? "rgba(16, 185, 129, 0.15)" : "transparent",
            "&:hover": { borderColor: "primary.main", bgcolor: "action.hover" },
          }}
          onClick={() => fileInputRef.current?.click()}
        >
          <Upload
            sx={{
              fontSize: 40,
              color: file ? "success.main" : "text.secondary",
              mb: 1,
            }}
          />
          <Typography
            variant="body1"
            color={file ? "success.main" : "text.secondary"}
          >
            {file
              ? file.name
              : "Haz clic para seleccionar el certificado (.p12 o .pfx)"}
          </Typography>
        </Box>

        <TextField
          label="PIN del Certificado"
          size="small"
          type="password"
          fullWidth
          value={pin}
          onChange={(e) => setPin(e.target.value)}
          placeholder="Ingrese el PIN"
          required
        />

        <Button
          type="submit"
          variant="contained"
          startIcon={<Upload />}
          disabled={mutation.isPending || !file || !pin}
          sx={{ alignSelf: "flex-start" }}
        >
          {mutation.isPending ? "Cargando..." : "Cargar Certificado"}
        </Button>
      </Box>
    </Paper>
  );
};
