import React, { useState } from "react";
import {
  Box,
  Button,
  Card,
  Chip,
  CircularProgress,
  Grid,
  Typography,
  IconButton,
  Tooltip,
} from "@mui/material";
import { useGetRolesQuery, useDeleteRoleMutation } from "../../../Api/attoDeskApi";
import { IRole } from "../../../Api/Interface/api.interface";
import { useStyles } from "../../../theme/appStyles";
import { useNotifier } from "../../../Core/Notifier";
import DeleteOutlineSharpIcon from "@mui/icons-material/DeleteOutlineSharp";
import EditSharpIcon from "@mui/icons-material/EditSharp";
import ShieldIcon from "@mui/icons-material/Shield";
import PeopleIcon from "@mui/icons-material/People";
import LockIcon from "@mui/icons-material/Lock";
import DeletePopup from "../../../Components/Delete/DeletePopup";
import CreateRoleModal from "./CreateRoleModal";

// ─── Action badge config ────────────────────────────────────────────────────
const ACTION_META: Record<string, { letter: string; color: string; bg: string; label: string }> = {
  view:   { letter: "V", color: "#1565C0", bg: "#E3F2FD", label: "View" },
  create: { letter: "C", color: "#2E7D32", bg: "#E8F5E9", label: "Create" },
  edit:   { letter: "E", color: "#E65100", bg: "#FFF3E0", label: "Edit" },
  delete: { letter: "D", color: "#B71C1C", bg: "#FFEBEE", label: "Delete" },
};

// ─── Sub-components ──────────────────────────────────────────────────────────
const ActionBadge = ({ action }: { action: string }) => {
  const meta = ACTION_META[action] ?? {
    letter: action[0].toUpperCase(),
    color: "#555",
    bg: "#F5F5F5",
    label: action,
  };
  return (
    <Tooltip title={meta.label} arrow>
      <Box
        component="span"
        sx={{
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          width: 20,
          height: 20,
          borderRadius: "50%",
          fontSize: "10px",
          fontWeight: 700,
          letterSpacing: 0,
          color: meta.color,
          backgroundColor: meta.bg,
          flexShrink: 0,
          cursor: "default",
          userSelect: "none",
        }}
      >
        {meta.letter}
      </Box>
    </Tooltip>
  );
};

const ModulePill = ({ label, actions }: { label: string; actions: string[] }) => (
  <Box
    sx={{
      display: "inline-flex",
      alignItems: "center",
      gap: 0.5,
      border: "1px solid",
      borderColor: "divider",
      borderRadius: "20px",
      px: 1.25,
      py: "3px",
      backgroundColor: "background.paper",
      fontSize: "12px",
      color: "text.primary",
      fontWeight: 500,
      whiteSpace: "nowrap",
    }}
  >
    {label}
    <Box sx={{ display: "flex", gap: 0.4, ml: 0.5 }}>
      {actions.map((a) => (
        <ActionBadge key={a} action={a} />
      ))}
    </Box>
  </Box>
);

// ─── Main Component ──────────────────────────────────────────────────────────
const Index = () => {
  const classes = useStyles();
  const { showErrorMessage, showMessage } = useNotifier();

  const { data, isLoading, isError } = useGetRolesQuery();
  const [deleteRole] = useDeleteRoleMutation();

  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [roleToEdit, setRoleToEdit] = useState<IRole | null>(null);
  const [roleToDelete, setRoleToDelete] = useState<IRole | null>(null);
  const [openDeletePopup, setOpenDeletePopup] = useState(false);

  const roles: IRole[] = data?.data ?? [];

  const handleOpenCreate = () => { setRoleToEdit(null); setCreateModalOpen(true); };
  const handleOpenEdit = (role: IRole) => { setRoleToEdit(role); setCreateModalOpen(true); };
  const handleCloseModal = () => { setCreateModalOpen(false); setRoleToEdit(null); };
  const handleOpenDeletePopup = (role: IRole) => { setRoleToDelete(role); setOpenDeletePopup(true); };
  const handleCloseDeletePopup = () => { setRoleToDelete(null); setOpenDeletePopup(false); };

  const handleDelete = async () => {
    if (!roleToDelete) return;
    try {
      await deleteRole(roleToDelete.id.toString()).unwrap();
      showMessage("Role deleted successfully");
      setOpenDeletePopup(false);
    } catch (error: any) {
      showErrorMessage(
        error?.data?.message || "Failed to delete role. It may still be assigned to team members."
      );
    }
  };

  if (isLoading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" height="10vh">
        <CircularProgress size={28} />
      </Box>
    );
  }

  return (
    <Card className={classes.card} sx={{ overflow: "hidden" }}>
      {/* ── Header ── */}
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          px: 3,
          py: 2.25,
          borderBottom: "1px solid",
          borderColor: "divider",
          backgroundColor: "background.paper",
        }}
      >
        <Box>
          <Typography variant="h6" sx={{ fontWeight: 600, lineHeight: 1.3 }}>
            User Roles
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 0.25 }}>
            Define roles and assign module permissions
          </Typography>
        </Box>
        <Button
          variant="contained"
          disableElevation
          onClick={handleOpenCreate}
          sx={{
            textTransform: "none",
            fontWeight: 600,
            fontSize: "13px",
            borderRadius: "8px",
            px: 2,
          }}
        >
          + Add Role
        </Button>
      </Box>

      {/* ── Role list ── */}
      <Box sx={{ px: 3, py: 2.5 }}>
        {isError || roles.length === 0 ? (
          <Box
            sx={{
              textAlign: "center",
              py: 6,
              borderRadius: 2,
              border: "1px dashed",
              borderColor: "divider",
              backgroundColor: "action.hover",
            }}
          >
            <ShieldIcon sx={{ fontSize: 36, color: "text.disabled", mb: 1 }} />
            <Typography color="text.secondary" fontSize="14px">
              {isError ? "Error fetching roles" : "No roles created yet"}
            </Typography>
            {!isError && (
              <Typography variant="caption" color="text.disabled">
                Click "+ Add Role" to create your first role
              </Typography>
            )}
          </Box>
        ) : (
          <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
            {roles.map((role) => (
              <Box
                key={role.id}
                sx={{
                  display: "flex",
                  alignItems: "flex-start",
                  justifyContent: "space-between",
                  gap: 2,
                  borderRadius: "10px",
                  border: "1px solid",
                  borderColor: "divider",
                  borderLeft: "3px solid",
                  borderLeftColor: role.is_system ? "warning.main" : "primary.main",
                  px: 2.25,
                  py: 1.75,
                  backgroundColor: "background.paper",
                  transition: "box-shadow 0.15s ease",
                  "&:hover": {
                    boxShadow: "0 2px 8px rgba(0,0,0,0.07)",
                  },
                }}
              >
                {/* Left: Info */}
                <Box sx={{ flex: 1, minWidth: 0 }}>
                  {/* Top row: name + meta chips */}
                  <Box sx={{ display: "flex", alignItems: "center", flexWrap: "wrap", gap: 1, mb: 0.5 }}>
                    <ShieldIcon sx={{ fontSize: 15, color: role.is_system ? "warning.main" : "primary.main" }} />
                    <Typography sx={{ fontWeight: 600, fontSize: "14px" }}>
                      {role.name}
                    </Typography>

                    {/* Users */}
                    <Box sx={{ display: "flex", alignItems: "center", gap: 0.4, color: "text.secondary" }}>
                      <PeopleIcon sx={{ fontSize: 13 }} />
                      <Typography variant="caption" sx={{ lineHeight: 1 }}>
                        {role.user_count} user{role.user_count !== 1 ? "s" : ""}
                      </Typography>
                    </Box>

                    {/* Permission count */}
                    <Chip
                      size="small"
                      label={`${role.permission_count} permissions`}
                      sx={{
                        height: 20,
                        fontSize: "11px",
                        fontWeight: 500,
                        backgroundColor: "#EEF4FF",
                        color: "#1D4ED8",
                        "& .MuiChip-label": { px: 1 },
                      }}
                    />

                    {/* System badge */}
                    {role.is_system && (
                      <Chip
                        size="small"
                        icon={<LockIcon sx={{ fontSize: "12px !important" }} />}
                        label="System"
                        variant="outlined"
                        sx={{
                          height: 20,
                          fontSize: "11px",
                          color: "warning.dark",
                          borderColor: "warning.main",
                          "& .MuiChip-label": { px: 0.75 },
                        }}
                      />
                    )}
                  </Box>

                  {/* Description */}
                  {role.description && (
                    <Typography
                      variant="body2"
                      color="text.secondary"
                      sx={{ fontSize: "12.5px", mb: 1, mt: 0.25 }}
                    >
                      {role.description}
                    </Typography>
                  )}

                  {/* Module pills */}
                  {role.modules?.length > 0 && (
                    <Box sx={{ display: "flex", flexWrap: "wrap", gap: 0.75, mt: role.description ? 0 : 0.75 }}>
                      {role.modules.map((m) => (
                        <ModulePill key={m.module} label={m.label} actions={m.actions} />
                      ))}
                    </Box>
                  )}
                </Box>

                {/* Right: Actions */}
                <Box sx={{ display: "flex", gap: 0.5, flexShrink: 0, mt: 0.25 }}>
                  <Tooltip title={role.is_system ? "System roles cannot be edited" : "Edit role"} arrow>
                    <span>
                      <IconButton
                        size="small"
                        onClick={() => handleOpenEdit(role)}
                        disabled={role.is_system}
                        sx={{
                          color: "primary.main",
                          border: "1px solid",
                          borderColor: "primary.light",
                          borderRadius: "7px",
                          width: 30,
                          height: 30,
                          "&:hover": { backgroundColor: "primary.50" },
                          "&.Mui-disabled": { borderColor: "divider", opacity: 0.4 },
                        }}
                      >
                        <EditSharpIcon sx={{ fontSize: 15 }} />
                      </IconButton>
                    </span>
                  </Tooltip>
                  <Tooltip title={role.is_system ? "System roles cannot be deleted" : "Delete role"} arrow>
                    <span>
                      <IconButton
                        size="small"
                        onClick={() => handleOpenDeletePopup(role)}
                        disabled={role.is_system}
                        sx={{
                          color: "error.main",
                          border: "1px solid",
                          borderColor: "error.light",
                          borderRadius: "7px",
                          width: 30,
                          height: 30,
                          "&:hover": { backgroundColor: "#FFF5F5" },
                          "&.Mui-disabled": { borderColor: "divider", opacity: 0.4 },
                        }}
                      >
                        <DeleteOutlineSharpIcon sx={{ fontSize: 15 }} />
                      </IconButton>
                    </span>
                  </Tooltip>
                </Box>
              </Box>
            ))}
          </Box>
        )}
      </Box>

      {/* ── Modals ── */}
      <CreateRoleModal
        open={createModalOpen}
        handleClose={handleCloseModal}
        roleToEdit={roleToEdit}
      />

      {roleToDelete && (
        <DeletePopup
          open={openDeletePopup}
          handleCloseDelete={handleCloseDeletePopup}
          onConfirm={handleDelete}
          title="Delete Role"
          content={`Are you sure you want to delete the "${roleToDelete.name}" role? This cannot be undone.`}
        />
      )}
    </Card>
  );
};

export default Index;