"use client";

import { useState } from "react";

import AddBoxOutlinedIcon from "@mui/icons-material/AddBoxOutlined";
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 type { MeetingRequest } from "../../meeting-request-data";

export function MeetingTitleCell({ row }: { row: MeetingRequest }) {
    return (
        <Typography
            sx={{
                width: "100%",
                overflow: "hidden",
                textOverflow: "ellipsis",
                fontSize: 13,
                fontWeight: 500,
                color: "var(--mr-text)",
                whiteSpace: "nowrap",
            }}
        >
            {row.title}
        </Typography>
    );
}

export function MeetingStatusCell({
    row,
    label,
}: {
    row: MeetingRequest;
    label: string;
}) {
    return (
        <MeetingRequestStatusBadge
            status={row.status}
            label={label || row.status}
        />
    );
}

export function MeetingIssueCell({ row }: { row: MeetingRequest }) {
    const { language } = useAppLanguage();

    return (
        <Box
            sx={{
                width: 30,
                height: 30,
                borderRadius: "50%",
                bgcolor: "var(--mr-red-bg)",
                color: "var(--mr-red-text)",
                fontSize: 13,
                fontWeight: 500,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
            }}
        >
            {formatNumber(row.issueCount, language)}
        </Box>
    );
}

export function MeetingDocumentCell({ row }: { row: MeetingRequest }) {
    const theme = useTheme();
    const label = row.meetingRequestLetter?.trim() || row.documentName;
    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 MeetingTextCell({
    value,
    align = "left",
    wrap = false,
}: {
    value: string | number;
    align?: "left" | "center" | "right";
    wrap?: boolean;
}) {
    return (
        <Typography
            sx={{
                width: "100%",
                overflow: "hidden",
                textOverflow: wrap ? "clip" : "ellipsis",
                fontSize: 13,
                fontWeight: 500,
                color: "var(--mr-text)",
                whiteSpace: wrap ? "normal" : "nowrap",
                textAlign: align,
                lineHeight: wrap ? 1.35 : 1.2,
                display: wrap ? "-webkit-box" : "block",
                WebkitLineClamp: wrap ? 2 : "unset",
                WebkitBoxOrient: wrap ? "vertical" : "unset",
                wordBreak: wrap ? "break-word" : "normal",
            }}
        >
            {value}
        </Typography>
    );
}

export function MeetingActionCell({
    row,
    onView,
    onCreateMeeting,
}: {
    row: MeetingRequest;
    onView?: (row: MeetingRequest) => void;
    onCreateMeeting?: (row: MeetingRequest) => void;
}) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";
    const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null);
    const canCreateMeeting = row.canCreateMeeting;

    function closeMenu() {
        setMenuAnchor(null);
    }

    function runAction(handler?: (row: MeetingRequest) => 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
                size="small"
                aria-label="More actions"
                onClick={(event) => setMenuAnchor(event.currentTarget)}
                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: 200,
                            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>

                {canCreateMeeting ? (
                    <MenuItem
                        onClick={() => runAction(onCreateMeeting)}
                        sx={{
                            ...menuItemSx,
                            "& .MuiListItemIcon-root": {
                                minWidth: 0,
                                color: isDark ? "#60A5FA" : "#1a64a8",
                            },
                        }}
                    >
                        <ListItemIcon>
                            <AddBoxOutlinedIcon sx={{ fontSize: 20 }} />
                        </ListItemIcon>
                        Create Meeting
                    </MenuItem>
                ) : null}
            </Menu>
        </>
    );
}
