"use client";

import { useState } from "react";

import Avatar from "@mui/material/Avatar";
import AvatarGroup from "@mui/material/AvatarGroup";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import AddIcon from "@mui/icons-material/Add";
import BusinessIcon from "@mui/icons-material/Business";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutlineOutlined";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";

import type {
  Stakeholder,
  StakeholderUser,
} from "@/features/stakeholder/stakeholder-data";

const API_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1";

function resolveLogoSrc(value: string | null | undefined) {
  if (!value) {
    return undefined;
  }

  if (value.startsWith("/uploads/")) {
    const backendUrl = API_URL.replace(/\/api(?:\/v\d+)?\/?$/, "");

    return `${backendUrl}${value}`;
  }

  return value;
}

const typeStyles: Record<
  string,
  { color: string; backgroundColor: string; borderColor: string }
> = {
  MINISTRY: {
    color: "#175cd3",
    backgroundColor: "#eff8ff",
    borderColor: "#b2ddff",
  },
  PRIVATE_SECTOR: {
    color: "#6941c6",
    backgroundColor: "#f9f5ff",
    borderColor: "#e9d7fe",
  },
  OTHER: {
    color: "#414651",
    backgroundColor: "#fafafa",
    borderColor: "#e9eaeb",
  },
};

function resolveAvatarSrc(value: string | null | undefined) {
  return resolveLogoSrc(value);
}

function getUserName(user: StakeholderUser) {
  return user.name?.trim() || user.email || `User #${user.id}`;
}

function getUserInitial(user: StakeholderUser) {
  return getUserName(user).charAt(0).toUpperCase();
}

const USER_AVATAR_GROUP_MAX = 6;

function getTypeStyle(type: string) {
  const normalizedType = type.toUpperCase().replace(/\s+/g, "_");

  return typeStyles[normalizedType] ?? typeStyles.OTHER;
}

export function TableText({
  value,
  fontSize = 13,
  fontWeight = 500,
  align = "left",
}: {
  value: string;
  fontSize?: number;
  fontWeight?: number;
  align?: "left" | "center";
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Typography
      noWrap
      sx={{
        width: "100%",
        color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
        fontSize,
        fontWeight,
        textAlign: align,
      }}
    >
      {value}
    </Typography>
  );
}

export function LogoCell({
  name,
  logo,
}: {
  name: string;
  logo: string | null;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      sx={{
        width: "100%",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Avatar
        src={resolveLogoSrc(logo)}
        alt={name}
        sx={{
          width: 60,
          height: 60,
          bgcolor: isDark ? alpha("#ffffff", 0.08) : "#f5f7fa",
          color: isDark ? alpha("#ffffff", 0.72) : "#1a64a8",
          fontSize: 16,
          fontWeight: 600,
        }}
      >
        {logo ? null : <BusinessIcon sx={{ fontSize: 24 }} />}
      </Avatar>
    </Box>
  );
}

export function StakeholderCell({ name }: { name: string }) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Typography
      noWrap
      sx={{
        width: "100%",
        color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
        fontSize: 13,
        fontWeight: 600,
      }}
    >
      {name}
    </Typography>
  );
}

export function TypeBadge({ type }: { type: string }) {
  const style = getTypeStyle(type);
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      sx={{
        px: 1,
        py: 0.25,
        borderRadius: "16px",
        border: `1px solid ${
          isDark ? alpha(style.borderColor, 0.4) : style.borderColor
        }`,
        backgroundColor: isDark
          ? alpha(style.backgroundColor, 0.12)
          : style.backgroundColor,
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Typography
        sx={{
          color: style.color,
          fontSize: 12,
          fontWeight: 500,
          lineHeight: "18px",
          whiteSpace: "nowrap",
        }}
      >
        {type}
      </Typography>
    </Box>
  );
}

export function StatusBadge({ active }: { active: boolean }) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  const style = active
    ? {
        color: "#12b76a",
        backgroundColor: "#ecfdf3",
        borderColor: "#d1fadf",
      }
    : {
        color: "#f04438",
        backgroundColor: "#fef3f2",
        borderColor: "#fee4e2",
      };

  return (
    <Box
      sx={{
        width: 80,
        height: 22,
        px: 1,
        borderRadius: "12px",
        border: `1px solid ${
          isDark ? alpha(style.borderColor, 0.4) : style.borderColor
        }`,
        backgroundColor: isDark
          ? alpha(style.backgroundColor, 0.12)
          : style.backgroundColor,
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Typography
        sx={{
          color: style.color,
          fontSize: 12,
          fontWeight: 500,
          lineHeight: 1,
        }}
      >
        {active ? "Active" : "Inactive"}
      </Typography>
    </Box>
  );
}

export function DescriptionCell({ value }: { value: string | null }) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Typography
      noWrap
      title={value ?? ""}
      sx={{
        width: "100%",
        color: isDark ? alpha("#ffffff", 0.72) : "#414651",
        fontSize: 13,
        fontWeight: 400,
      }}
    >
      {value && value.length > 0 ? value : "-"}
    </Typography>
  );
}

export function UsersCell({
  users,
  align = "center",
}: {
  users: StakeholderUser[];
  align?: "left" | "center";
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const avatarBorderColor = isDark ? "#101828" : "#ffffff";

  if (users.length === 0) {
    return <TableText value="-" align={align} />;
  }

  return (
    <Box
      sx={{
        width: align === "center" ? "100%" : "auto",
        display: "flex",
        alignItems: "center",
        justifyContent: align === "center" ? "center" : "flex-start",
      }}
    >
      <AvatarGroup
        max={USER_AVATAR_GROUP_MAX}
        sx={{
          "& .MuiAvatar-root": {
            width: 24,
            height: 24,
            fontSize: 12,
            fontWeight: 600,
            lineHeight: "18px",
            bgcolor: isDark ? alpha("#ffffff", 0.08) : "#e0e0e0",
            color: isDark ? alpha("#ffffff", 0.72) : "#414651",
            border: `1.5px solid ${avatarBorderColor}`,
            boxSizing: "border-box",
          },
          "& .MuiAvatarGroup-avatar": {
            width: 24,
            height: 24,
            fontSize: 12,
            fontWeight: 600,
            lineHeight: "18px",
            bgcolor: isDark ? alpha("#ffffff", 0.06) : "#f5f5f5",
            color: isDark ? alpha("#ffffff", 0.72) : "#414651",
            border: `2px solid ${avatarBorderColor}`,
            boxSizing: "border-box",
          },
        }}
      >
        {users.map((user) => (
          <Tooltip key={String(user.id)} title={getUserName(user)} arrow>
            <Avatar
              src={resolveAvatarSrc(user.avatar)}
              alt={getUserName(user)}
            >
              {getUserInitial(user)}
            </Avatar>
          </Tooltip>
        ))}
      </AvatarGroup>
    </Box>
  );
}

type ActionCellProps = {
  stakeholder: Stakeholder;
  onView: (stakeholder: Stakeholder) => void;
  onAddUser: (stakeholder: Stakeholder) => void;
  onEdit: (stakeholder: Stakeholder) => void;
  onDelete: (stakeholder: Stakeholder) => void;
};

export function ActionCell({
  stakeholder,
  onView,
  onAddUser,
  onEdit,
  onDelete,
}: ActionCellProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  const [menuAnchorEl, setMenuAnchorEl] = useState<HTMLElement | null>(null);

  function closeMenu() {
    setMenuAnchorEl(null);
  }

  return (
    <>
      <IconButton
        onClick={(event) => setMenuAnchorEl(event.currentTarget)}
        size="small"
        sx={{
          width: 28,
          height: 28,
          borderRadius: "4px",
          color: isDark ? alpha("#ffffff", 0.72) : "#717680",
        }}
      >
        <MoreVertIcon sx={{ fontSize: 18 }} />
      </IconButton>

      <Menu
        anchorEl={menuAnchorEl}
        open={Boolean(menuAnchorEl)}
        onClose={closeMenu}
        anchorOrigin={{ vertical: "center", horizontal: "left" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              width: 160,
              borderRadius: "8px",
              border: `1px solid ${
                isDark ? alpha("#ffffff", 0.1) : "#f5f5f5"
              }`,
              backgroundColor: isDark ? "#101828" : "#ffffff",
              boxShadow: isDark
                ? "0px 0px 20px rgba(0,0,0,0.45)"
                : "0px 0px 10.6px rgba(0, 0, 0, 0.1)",
              mt: 0.5,
            },
          },
          list: {
            disablePadding: true,
          },
        }}
      >
        <MenuItem
          onClick={() => {
            closeMenu();
            onView(stakeholder);
          }}
          sx={{
            height: 40,
            gap: 1,
            color: isDark ? alpha("#ffffff", 0.75) : "#717680",
            fontSize: 13,
            fontWeight: 400,
            "&:hover": {
              backgroundColor: isDark ? alpha("#ffffff", 0.06) : "#f9fafb",
            },
          }}
        >
          <VisibilityOutlinedIcon sx={{ fontSize: 18 }} />
          View
        </MenuItem>

        <MenuItem
          onClick={() => {
            closeMenu();
            onAddUser(stakeholder);
          }}
          sx={{
            height: 40,
            gap: 1,
            color: isDark ? alpha("#ffffff", 0.75) : "#717680",
            fontSize: 13,
            fontWeight: 400,
            "&:hover": {
              backgroundColor: isDark ? alpha("#ffffff", 0.06) : "#f9fafb",
            },
          }}
        >
          <AddIcon sx={{ fontSize: 18 }} />
          Add user
        </MenuItem>

        <MenuItem
          onClick={() => {
            closeMenu();
            onEdit(stakeholder);
          }}
          sx={{
            height: 40,
            gap: 1,
            color: isDark ? alpha("#ffffff", 0.75) : "#717680",
            fontSize: 13,
            fontWeight: 400,
            "&:hover": {
              backgroundColor: isDark ? alpha("#ffffff", 0.06) : "#f9fafb",
            },
          }}
        >
          <EditOutlinedIcon sx={{ fontSize: 18 }} />
          Edit
        </MenuItem>

        <MenuItem
          onClick={() => {
            closeMenu();
            onDelete(stakeholder);
          }}
          sx={{
            height: 40,
            gap: 1,
            color: "#f04438",
            fontSize: 13,
            fontWeight: 400,
            borderTop: `1px solid ${isDark ? alpha("#ffffff", 0.08) : "#f5f5f5"}`,
            "&:hover": {
              backgroundColor: isDark ? alpha("#ffffff", 0.06) : "#fef3f2",
            },
          }}
        >
          <DeleteOutlineIcon sx={{ fontSize: 18 }} />
          Delete
        </MenuItem>
      </Menu>
    </>
  );
}
