import {
    Add,
    AutoAwesome,
    Business,
    ContentCopy,
    Delete,
    Edit,
    Security,
    VerifiedUser,
} from "@mui/icons-material";
import {
    Box,
    Button,
    Card,
    CardContent,
    Chip,
    CircularProgress,
    IconButton,
    Paper,
    Stack,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Tooltip,
    Typography,
    useMediaQuery,
    useTheme,
} from "@mui/material";
import { useState } from "react";
import { usePermission } from "../../../hooks/usePermission";
import {
    useCargarPerfilesSugeridosMutation,
    useClonarPerfilMutation,
    useEliminarPerfilMutation,
    usePerfilesV2Query,
} from "../../../tanstack/SeguridadStack";
import { AccesoRestringido } from "../../common/AccesoRestringido";
import { PerfilFormDialog } from "./PerfilFormDialog";

export const PerfilesListConfig = () => {
  const muiTheme = useTheme();
  const isMobile = useMediaQuery(muiTheme.breakpoints.down("sm"));
  const { canRead, canCreate, canEdit, canDelete } =
    usePermission("CONFIG_PERFILES");
  const { data: perfilesData, isLoading } = usePerfilesV2Query();
  const deleteMutation = useEliminarPerfilMutation();
  const clonarMutation = useClonarPerfilMutation();
  const sugeridosMutation = useCargarPerfilesSugeridosMutation();

  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedPerfil, setSelectedPerfil] = useState(null);

  const perfiles = perfilesData || [];

  const handleOpenCreate = () => {
    setSelectedPerfil(null);
    setDialogOpen(true);
  };

  const handleOpenEdit = (perfil) => {
    setSelectedPerfil(perfil);
    setDialogOpen(true);
  };

  const handleDelete = async (perfil) => {
    if (perfil.is_sistema) return;
    if (window.confirm(`¿Eliminar el perfil "${perfil.perfil}"?`)) {
      await deleteMutation.mutateAsync(perfil.id);
    }
  };

  const handleClonar = async (perfil) => {
    await clonarMutation.mutateAsync(perfil.id);
  };

  const handleCargarSugeridos = async () => {
    await sugeridosMutation.mutateAsync();
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
    setSelectedPerfil(null);
  };

  if (!canRead) {
    return (
      <AccesoRestringido mensaje="No tienes permisos para ver los perfiles." />
    );
  }

  if (isLoading) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ maxWidth: 1200, mx: "auto" }}>
      {/* Header */}
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 3,
          gap: 1,
        }}
      >
        <Box>
          <Typography
            variant="h5"
            fontWeight={600}
            sx={{ fontSize: { xs: "1.1rem", sm: "1.5rem" } }}
          >
            Gestión de Perfiles
          </Typography>
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{ fontSize: { xs: "0.75rem", sm: "0.875rem" } }}
          >
            Define los roles y permisos de tu equipo
          </Typography>
        </Box>
        <Stack direction="row" spacing={1} flexShrink={0}>
          {canCreate && perfiles.length === 0 && (
            <Tooltip title="Crea automáticamente los perfiles del sistema (Administrador, Cajero, Vendedor, etc.)">
              <Button
                variant="outlined"
                startIcon={<AutoAwesome />}
                onClick={handleCargarSugeridos}
                disabled={sugeridosMutation.isPending}
                size={isMobile ? "small" : "medium"}
                sx={{ whiteSpace: "nowrap" }}
              >
                {isMobile ? "Sugeridos" : "Cargar sugeridos"}
              </Button>
            </Tooltip>
          )}
          {canCreate && (
            <Button
              variant="contained"
              startIcon={<Add />}
              onClick={handleOpenCreate}
              size={isMobile ? "small" : "medium"}
              sx={{ whiteSpace: "nowrap" }}
            >
              {isMobile ? "Nuevo" : "Nuevo Perfil"}
            </Button>
          )}
        </Stack>
      </Box>

      {/* Vista mobile: cards */}
      {isMobile ? (
        <Stack spacing={1.5}>
          {perfiles.length === 0 ? (
            <Box sx={{ textAlign: "center", py: 4 }}>
              <Security sx={{ fontSize: 40, color: "text.secondary", mb: 1 }} />
              <Typography color="text.secondary" variant="body2">
                No hay perfiles registrados
              </Typography>
            </Box>
          ) : (
            perfiles.map((perfil) => (
              <Card key={perfil.id} variant="outlined" sx={{ borderRadius: 2 }}>
                <CardContent sx={{ p: "12px !important" }}>
                  {/* Nombre + tipo + estado */}
                  <Box
                    sx={{
                      display: "flex",
                      alignItems: "flex-start",
                      justifyContent: "space-between",
                      mb: 0.75,
                      gap: 1,
                    }}
                  >
                    <Box
                      sx={{
                        display: "flex",
                        alignItems: "center",
                        gap: 0.75,
                        minWidth: 0,
                      }}
                    >
                      <Security
                        color="action"
                        fontSize="small"
                        sx={{ flexShrink: 0 }}
                      />
                      <Typography variant="subtitle2" fontWeight={600} noWrap>
                        {perfil.perfil}
                      </Typography>
                    </Box>
                    <Box sx={{ display: "flex", gap: 0.5, flexShrink: 0 }}>
                      {perfil.is_sistema ? (
                        <Chip
                          icon={<VerifiedUser fontSize="small" />}
                          label="SISTEMA"
                          size="small"
                          color="default"
                          variant="filled"
                        />
                      ) : (
                        <Chip
                          icon={<Business fontSize="small" />}
                          label="EMPRESA"
                          size="small"
                          color="success"
                          variant="outlined"
                          sx={{ fontWeight: "bold" }}
                        />
                      )}
                      <Chip label="Activo" size="small" color="success" />
                    </Box>
                  </Box>
                  {/* Descripción */}
                  {perfil.desc_perfil && (
                    <Typography
                      variant="caption"
                      color="text.secondary"
                      sx={{ display: "block", mb: 0.75 }}
                    >
                      {perfil.desc_perfil}
                    </Typography>
                  )}
                  {/* Acciones */}
                  <Box
                    sx={{
                      display: "flex",
                      gap: 0.5,
                      justifyContent: "flex-end",
                      borderTop: "1px solid",
                      borderColor: "divider",
                      pt: 1,
                      mt: 0.5,
                    }}
                  >
                    {canEdit && (
                      <Tooltip title={perfil.is_sistema ? "Ver (solo lectura)" : "Editar"}>
                        <IconButton size="small" onClick={() => handleOpenEdit(perfil)}>
                          <Edit fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                    {canCreate && (
                      <Tooltip title="Clonar">
                        <IconButton
                          size="small"
                          onClick={() => handleClonar(perfil)}
                          disabled={clonarMutation.isPending}
                        >
                          <ContentCopy fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                    {canDelete && !perfil.is_sistema && (
                      <Tooltip title="Eliminar">
                        <IconButton
                          size="small"
                          color="error"
                          onClick={() => handleDelete(perfil)}
                        >
                          <Delete fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                  </Box>
                </CardContent>
              </Card>
            ))
          )}
        </Stack>
      ) : (
        /* Vista desktop: tabla */
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Perfil</TableCell>
                <TableCell>Descripción</TableCell>
                <TableCell>Tipo</TableCell>
                <TableCell>Estado</TableCell>
                <TableCell align="right">Acciones</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {perfiles.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} align="center" sx={{ py: 4 }}>
                    <Security
                      sx={{ fontSize: 48, color: "text.secondary", mb: 1 }}
                    />
                    <Typography color="text.secondary">
                      No hay perfiles registrados
                    </Typography>
                  </TableCell>
                </TableRow>
              ) : (
                perfiles.map((perfil) => (
                  <TableRow key={perfil.id}>
                    <TableCell>
                      <Box
                        sx={{ display: "flex", alignItems: "center", gap: 1 }}
                      >
                        <Security color="action" fontSize="small" />
                        <Typography fontWeight={500}>
                          {perfil.perfil}
                        </Typography>
                      </Box>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" color="text.secondary">
                        {perfil.desc_perfil || "-"}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      {perfil.is_sistema ? (
                        <Chip
                          icon={<VerifiedUser fontSize="small" />}
                          label="SISTEMA"
                          size="small"
                          color="default"
                          variant="filled"
                        />
                      ) : (
                        <Chip
                          icon={<Business fontSize="small" />}
                          label="EMPRESA"
                          size="small"
                          color="success"
                          variant="outlined"
                          sx={{ fontWeight: "bold" }}
                        />
                      )}
                    </TableCell>
                    <TableCell>
                      <Chip
                        label="Activo"
                        size="small"
                        color="success"
                        variant="soft"
                      />
                    </TableCell>
                    <TableCell align="right">
                      <Box>
                        {canEdit && (
                          <Tooltip title={perfil.is_sistema ? "Ver (solo lectura)" : "Editar"}>
                            <IconButton size="small" onClick={() => handleOpenEdit(perfil)}>
                              <Edit fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        )}
                        {canCreate && (
                          <Tooltip title="Clonar">
                            <IconButton
                              size="small"
                              onClick={() => handleClonar(perfil)}
                              disabled={clonarMutation.isPending}
                            >
                              <ContentCopy fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        )}
                        {canDelete && !perfil.is_sistema && (
                          <Tooltip title="Eliminar">
                            <IconButton
                              size="small"
                              color="error"
                              onClick={() => handleDelete(perfil)}
                            >
                              <Delete fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        )}
                      </Box>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      <PerfilFormDialog
        open={dialogOpen}
        onClose={handleCloseDialog}
        perfil={selectedPerfil}
      />
    </Box>
  );
};
