"use client";

import { useState } from "react";

import AddBoxOutlinedIcon from "@mui/icons-material/AddBoxOutlined";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import MoreVertIcon from "@mui/icons-material/MoreVert";
import VisibilityOutlinedIcon from "@mui/icons-material/VisibilityOutlined";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { DocumentLink } from "@/components/ui/document-link";
import { PdfDocumentIcon } from "@/components/ui/pdf-document-icon";
import { MeetingRequestStatusBadge } from "@/components/ui/meeting-request-status-badge";
import {
  formatDocumentCellValue,
  isDocumentPlaceholder,
  truncateFileName,
} from "@/lib/document-file";
import { formatNumber } from "@/lib/number-utils";

import {
  canEditMeetingCalendarRow,
  canUseMeetingSummaryAction,
  getMeetingSummaryAction,
  type MeetingCalendarRow,
  type MeetingCalendarStatus,
} from "../../meeting-calendar-data";

export function MeetingCalendarTextCell({
  value,
  khmer = false,
  wrap = false,
}: {
  value: string;
  khmer?: boolean;
  wrap?: boolean;
}) {
  return (
    <Typography
      title={value}
      noWrap={!wrap}
      sx={{
        color: "var(--calendar-text)",
        fontFamily: khmer ? "var(--font-khmer)" : "inherit",
        fontSize: 13,
        fontWeight: 500,
        lineHeight: 1.3,
        ...(wrap && {
          whiteSpace: "normal",
          wordBreak: "break-word",
          display: "-webkit-box",
          WebkitLineClamp: 2,
          WebkitBoxOrient: "vertical",
          overflow: "hidden",
        }),
      }}
    >
      {value}
    </Typography>
  );
}

export function MeetingCalendarIssueCell({ count }: { count: number }) {
  const { language } = useAppLanguage();
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  return (
    <Box
      sx={{
        width: 30,
        height: 30,
        borderRadius: "50%",
        bgcolor: isDark ? "#3B2B3A" : "#FFFBFA",
        color: isDark ? "#FCA5A5" : "#F04438",
        fontSize: 13,
        fontWeight: 500,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        flexShrink: 0,
      }}
    >
      {formatNumber(count, language)}
    </Box>
  );
}

export function MeetingCalendarDocumentCell({ label }: { label: string }) {
  const theme = useTheme();
  const hasDocument = !isDocumentPlaceholder(label);
  const displayLabel = formatDocumentCellValue(label, "-");
  const shortLabel = hasDocument ? truncateFileName(displayLabel) : displayLabel;

  return (
    <Box
      onClick={(event) => event.stopPropagation()}
      onMouseDown={(event) => event.stopPropagation()}
      sx={{
        width: "100%",
        height: "100%",
        minWidth: 0,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <DocumentLink
        file={hasDocument ? { path: label } : null}
        sx={{
          maxWidth: "100%",
          minWidth: 0,
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 0.75,
          overflow: "hidden",
        }}
      >
        {hasDocument ? <PdfDocumentIcon size={20} /> : null}

        <Typography
          sx={{
            color: theme.palette.text.primary,
            fontSize: 13,
            lineHeight: 1.5,
            minWidth: 0,
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          {shortLabel}
        </Typography>
      </DocumentLink>
    </Box>
  );
}

export function MeetingCalendarStatusCell({
  status,
}: {
  status: MeetingCalendarStatus;
}) {
  return (
    <MeetingRequestStatusBadge status={status} sx={{ width: 105 }} />
  );
}

export function MeetingCalendarActionCell({
  row,
  onView,
  onEdit,
  onCreateMeetingSummary,
}: {
  row: MeetingCalendarRow;
  onView?: (row: MeetingCalendarRow) => void;
  onEdit?: (row: MeetingCalendarRow) => void;
  onCreateMeetingSummary?: (row: MeetingCalendarRow) => void;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);
  const meetingSummaryAction = getMeetingSummaryAction(row.meetingSummaryId);
  const editAllowed = canEditMeetingCalendarRow(row);
  const hasMeetingSummary = row.meetingSummaryId !== null;
  const summaryActionAllowed = canUseMeetingSummaryAction(row);

  function closeMenu() {
    setMenuAnchor(null);
  }

  function runAction(handler?: (row: MeetingCalendarRow) => void) {
    closeMenu();
    if (handler) {
      handler(row);
    }
  }

  const menuItemSx = {
    gap: 1.25,
    px: 2,
    py: 1.25,
    fontSize: 14,
    color: isDark ? alpha("#ffffff", 0.78) : "#414651",
    "& .MuiListItemIcon-root": {
      minWidth: 0,
      color: "inherit",
    },
  };

  return (
    <>
      <IconButton
        aria-label={`Open actions for ${row.title}`}
        onClick={(event) => {
          event.stopPropagation();
          setMenuAnchor(event.currentTarget);
        }}
        size="small"
        sx={{
          width: 32,
          height: 32,
          color: isDark ? alpha("#ffffff", 0.55) : "#717680",
          "&:hover": {
            bgcolor: isDark ? alpha("#ffffff", 0.06) : alpha("#000000", 0.04),
          },
        }}
      >
        <MoreVertIcon sx={{ fontSize: 20 }} />
      </IconButton>

      <Menu
        anchorEl={menuAnchor}
        open={Boolean(menuAnchor)}
        onClose={closeMenu}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              minWidth: 220,
              borderRadius: "10px",
              boxShadow: isDark
                ? "0 0 20px rgba(0,0,0,0.45)"
                : "0 4px 16px rgba(0,0,0,0.12)",
            },
          },
        }}
      >
        <MenuItem onClick={() => runAction(onView)} sx={menuItemSx}>
          <ListItemIcon>
            <VisibilityOutlinedIcon sx={{ fontSize: 20 }} />
          </ListItemIcon>
          View Detail
        </MenuItem>

        {editAllowed ? (
          <Box>
            <MenuItem
              onClick={() => runAction(onEdit)}
              sx={{ ...menuItemSx, width: "100%" }}
            >
              <ListItemIcon>
                <EditOutlinedIcon sx={{ fontSize: 20 }} />
              </ListItemIcon>
              Edit
            </MenuItem>
          </Box>
        ) : null}

        {hasMeetingSummary || summaryActionAllowed ? (
          <Box>
            <MenuItem
              onClick={() => runAction(onCreateMeetingSummary)}
              sx={{
                ...menuItemSx,
                width: "100%",
                "& .MuiListItemIcon-root": {
                  minWidth: 0,
                  color: isDark ? "#60A5FA" : "#1a64a8",
                },
              }}
            >
              <ListItemIcon>
                {hasMeetingSummary ? (
                  <VisibilityOutlinedIcon sx={{ fontSize: 20 }} />
                ) : (
                  <AddBoxOutlinedIcon sx={{ fontSize: 20 }} />
                )}
              </ListItemIcon>
              {meetingSummaryAction.label}
            </MenuItem>
          </Box>
        ) : null}
      </Menu>
    </>
  );
}
