"use client";

import {
    useMemo,
    useRef,
    useState,
    type ComponentProps,
    type MouseEvent,
} from "react";

import {
    Avatar,
    Box,
    Button,
    Card,
    CardContent,
    Chip,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    Divider,
    FormControl,
    IconButton,
    InputAdornment,
    Menu,
    MenuItem,
    Paper,
    Select,
    SvgIcon,
    TextField,
    Typography,
    useTheme,
} from "@mui/material";

import { useAppLanguage } from "@/components/providers/app-language-provider";

type Lang = "en" | "kh";
type CommentStatus = "Pending" | "Reviewed" | "Resolved";

type UserComment = {
    id: number;
    userName: string;
    email: string;
    avatar?: string;
    commentType: string;
    message: string;
    messageKm: string;
    status: CommentStatus;
    createdAt: string;
};

const TEXT = {
    en: {
        title: "User Comments",
        subtitle: "View user comments and manage comment status",
        totalComments: "Total Comments",
        allUserComments: "All user comments",
        pending: "Pending",
        needReview: "Need review",
        reviewed: "Reviewed",
        alreadyReviewed: "Already reviewed",
        resolved: "Resolved",
        issueResolved: "Issue resolved",
        search: "Search...",
        commentType: "Comment Type",
        allTypes: "All Types",
        status: "Status",
        allStatus: "All Status",
        no: "No",
        user: "User",
        commentMessage: "Comment Message",
        createdDate: "Created Date",
        actions: "Actions",
        previous: "Previous",
        next: "Next",
        noData: "No data",
        noMatchingData: "No matching data",
        noDataMessage: "There are no comments to show.",
        noMatchingMessage: "Try clearing the search or filter options.",
        clearFilters: "Clear filters",
        editComment: "Edit Comment",
        viewHistory: "View History",
        toggleStatus: "Toggle Status",
        deleteComment: "Delete Comment",
        commentDetail: "Comment Detail",
        userName: "User Name",
        email: "Email",
        message: "Message",
        close: "Close",
        markResolved: "Mark as Resolved",
        deleteTitle: "Delete Comment?",
        deleteBefore: "Are you sure you want to delete comment from",
        cancel: "Cancel",
        delete: "Delete",
    },
    kh: {
        title: "មតិយោបល់អ្នកប្រើប្រាស់",
        subtitle: "មើលមតិយោបល់ និងគ្រប់គ្រងស្ថានភាពមតិយោបល់",
        totalComments: "មតិយោបល់សរុប",
        allUserComments: "មតិយោបល់អ្នកប្រើប្រាស់ទាំងអស់",
        pending: "កំពុងរង់ចាំ",
        needReview: "ត្រូវការពិនិត្យ",
        reviewed: "បានពិនិត្យ",
        alreadyReviewed: "បានពិនិត្យរួច",
        resolved: "បានដោះស្រាយ",
        issueResolved: "បញ្ហាបានដោះស្រាយ",
        search: "ស្វែងរក...",
        commentType: "ប្រភេទមតិយោបល់",
        allTypes: "ប្រភេទទាំងអស់",
        status: "ស្ថានភាព",
        allStatus: "ស្ថានភាពទាំងអស់",
        no: "ល.រ",
        user: "អ្នកប្រើប្រាស់",
        commentMessage: "សារមតិយោបល់",
        createdDate: "កាលបរិច្ឆេទបង្កើត",
        actions: "សកម្មភាព",
        previous: "មុន",
        next: "បន្ទាប់",
        noData: "មិនមានទិន្នន័យ",
        noMatchingData: "មិនមានទិន្នន័យត្រូវគ្នា",
        noDataMessage: "មិនមានមតិយោបល់សម្រាប់បង្ហាញទេ។",
        noMatchingMessage: "សូមលុបការស្វែងរក ឬ filter ចេញ។",
        clearFilters: "លុប Filter",
        editComment: "កែប្រែមតិយោបល់",
        viewHistory: "មើលប្រវត្តិ",
        toggleStatus: "ប្ដូរស្ថានភាព",
        deleteComment: "លុបមតិយោបល់",
        commentDetail: "ព័ត៌មានលម្អិតមតិយោបល់",
        userName: "ឈ្មោះអ្នកប្រើប្រាស់",
        email: "អ៊ីមែល",
        message: "សារ",
        close: "បិទ",
        markResolved: "កំណត់ថាបានដោះស្រាយ",
        deleteTitle: "លុបមតិយោបល់?",
        deleteBefore: "តើអ្នកពិតជាចង់លុបមតិយោបល់ពី",
        cancel: "បោះបង់",
        delete: "លុប",
    },
} as const;

const COMMENT_TYPE_LABELS: Record<Lang, Record<string, string>> = {
    en: {
        Suggestion: "Suggestion",
        Complaint: "Complaint",
        Question: "Question",
    },
    kh: {
        Suggestion: "សំណើ",
        Complaint: "បណ្ដឹង",
        Question: "សំណួរ",
    },
};

const STATUS_LABELS: Record<Lang, Record<CommentStatus, string>> = {
    en: {
        Pending: "Pending",
        Reviewed: "Reviewed",
        Resolved: "Resolved",
    },
    kh: {
        Pending: "កំពុងរង់ចាំ",
        Reviewed: "បានពិនិត្យ",
        Resolved: "បានដោះស្រាយ",
    },
};

const initialComments: UserComment[] = [
    {
        id: 1,
        userName: "Dara Sok",
        email: "dara@gmail.com",
        avatar: "/images/users/user-1.jpg",
        commentType: "Suggestion",
        message: "Please add download report feature.",
        messageKm: "សូមបន្ថែមមុខងារទាញយករបាយការណ៍។",
        status: "Resolved",
        createdAt: "2026-05-28 09:30 AM",
    },
    {
        id: 2,
        userName: "Sopheak Chan",
        email: "sopheak@gmail.com",
        avatar: "/images/users/user-2.jpg",
        commentType: "Complaint",
        message: "Login page sometimes loads slowly.",
        messageKm: "ទំព័រ Login ពេលខ្លះដំណើរការយឺត។",
        status: "Resolved",
        createdAt: "2026-05-27 02:15 PM",
    },
    {
        id: 3,
        userName: "Admin Test",
        email: "admin@test.com",
        avatar: "/images/users/user-3.jpg",
        commentType: "Question",
        message: "How can I export the user list?",
        messageKm: "តើខ្ញុំអាច Export បញ្ជីអ្នកប្រើប្រាស់ដោយរបៀបណា?",
        status: "Resolved",
        createdAt: "2026-05-26 11:00 AM",
    },
    {
        id: 4,
        userName: "Virak Kim",
        email: "virak@gmail.com",
        avatar: "/images/users/user-4.jpg",
        commentType: "Suggestion",
        message: "Please improve dashboard spacing.",
        messageKm: "សូមកែលម្អចន្លោះក្នុង Dashboard។",
        status: "Pending",
        createdAt: "2026-05-25 04:45 PM",
    },
    {
        id: 5,
        userName: "Sokha Lin",
        email: "sokha@gmail.com",
        avatar: "/images/users/user-5.jpg",
        commentType: "Suggestion",
        message: "Please improve notifications.",
        messageKm: "សូមកែលម្អការជូនដំណឹង។",
        status: "Pending",
        createdAt: "2026-05-24 01:30 PM",
    },
    {
        id: 6,
        userName: "Ratha Kim",
        email: "ratha@gmail.com",
        avatar: "/images/users/user-6.jpg",
        commentType: "Complaint",
        message: "Some pages are slow on mobile.",
        messageKm: "ទំព័រខ្លះដំណើរការយឺតលើទូរស័ព្ទ។",
        status: "Reviewed",
        createdAt: "2026-05-23 10:20 AM",
    },
    {
        id: 7,
        userName: "Vanda Chea",
        email: "vanda@gmail.com",
        avatar: "/images/users/user-7.jpg",
        commentType: "Question",
        message: "Can admin see user comments?",
        messageKm: "តើ Admin អាចមើលមតិយោបល់របស់អ្នកប្រើប្រាស់បានទេ?",
        status: "Resolved",
        createdAt: "2026-05-22 08:10 AM",
    },
    {
        id: 8,
        userName: "Nita Long",
        email: "nita@gmail.com",
        avatar: "/images/users/user-8.jpg",
        commentType: "Question",
        message: "How do I update my profile information?",
        messageKm: "តើខ្ញុំអាចកែប្រែព័ត៌មាន Profile របស់ខ្ញុំដោយរបៀបណា?",
        status: "Reviewed",
        createdAt: "2026-05-21 03:25 PM",
    },
    {
        id: 9,
        userName: "Seyha Pov",
        email: "seyha@gmail.com",
        avatar: "/images/users/user-9.jpg",
        commentType: "Suggestion",
        message: "Please add export Excel button.",
        messageKm: "សូមបន្ថែមប៊ូតុង Export Excel។",
        status: "Pending",
        createdAt: "2026-05-20 09:40 AM",
    },
    {
        id: 10,
        userName: "Mony Rath",
        email: "mony@gmail.com",
        avatar: "/images/users/user-10.jpg",
        commentType: "Complaint",
        message: "The search box should be wider.",
        messageKm: "ប្រអប់ស្វែងរកគួរតែធំជាងនេះ។",
        status: "Resolved",
        createdAt: "2026-05-19 12:00 PM",
    },
    {
        id: 11,
        userName: "Pisey Chan",
        email: "pisey@gmail.com",
        avatar: "/images/users/user-11.jpg",
        commentType: "Question",
        message: "How to change user role?",
        messageKm: "តើប្ដូរ Role អ្នកប្រើប្រាស់ដោយរបៀបណា?",
        status: "Pending",
        createdAt: "2026-05-18 02:15 PM",
    },
    {
        id: 12,
        userName: "Bora Heng",
        email: "bora@gmail.com",
        avatar: "/images/users/user-12.jpg",
        commentType: "Complaint",
        message: "The table should keep pagination fixed.",
        messageKm: "តារាងគួររក្សាទីតាំង Pagination ឱ្យនៅដដែល។",
        status: "Reviewed",
        createdAt: "2026-05-17 05:30 PM",
    },
];

const TABLE_COLUMNS =
    "58px minmax(205px, 0.9fr) 145px minmax(230px, 1.2fr) 120px 165px 96px";

const ROW_HEIGHT = 70;
const FIXED_BODY_HEIGHT = ROW_HEIGHT * 10;

export default function AdminCommentTypesPage() {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";

    const { language } = useAppLanguage();
    const lang: Lang = language === "kh" ? "kh" : "en";
    const isKhmer = lang === "kh";
    const t = TEXT[lang];

    const getCommentTypeLabel = (type: string) => {
        return COMMENT_TYPE_LABELS[lang][type] ?? type;
    };

    const getStatusLabel = (status: CommentStatus) => {
        return STATUS_LABELS[lang][status] ?? status;
    };

    const getMessage = (row: UserComment) => {
        return isKhmer ? row.messageKm : row.message;
    };

    const [rows, setRows] = useState<UserComment[]>(initialComments);
    const [search, setSearch] = useState("");
    const [typeFilter, setTypeFilter] = useState("All");
    const [statusFilter, setStatusFilter] = useState<"All" | CommentStatus>("All");
    const [page, setPage] = useState(0);

    const rowsPerPage = 10;

    const [viewRow, setViewRow] = useState<UserComment | null>(null);
    const [deleteRow, setDeleteRow] = useState<UserComment | null>(null);
    const [actionAnchorEl, setActionAnchorEl] = useState<HTMLElement | null>(null);
    const actionRowRef = useRef<UserComment | null>(null);

    const columnBorder = isDark
        ? "1px solid rgba(148,163,184,0.14)"
        : "1px solid #E5EAF2";

    const filteredRows = useMemo(() => {
        return rows.filter((item) => {
            const keyword = search.trim().toLowerCase();

            const typeLabelEn = COMMENT_TYPE_LABELS.en[item.commentType] ?? item.commentType;
            const typeLabelKh = COMMENT_TYPE_LABELS.kh[item.commentType] ?? item.commentType;
            const statusLabelEn = STATUS_LABELS.en[item.status] ?? item.status;
            const statusLabelKh = STATUS_LABELS.kh[item.status] ?? item.status;

            const matchSearch =
                !keyword ||
                item.userName.toLowerCase().includes(keyword) ||
                item.email.toLowerCase().includes(keyword) ||
                item.message.toLowerCase().includes(keyword) ||
                item.messageKm.toLowerCase().includes(keyword) ||
                item.commentType.toLowerCase().includes(keyword) ||
                typeLabelEn.toLowerCase().includes(keyword) ||
                typeLabelKh.toLowerCase().includes(keyword) ||
                statusLabelEn.toLowerCase().includes(keyword) ||
                statusLabelKh.toLowerCase().includes(keyword);

            const matchType = typeFilter === "All" || item.commentType === typeFilter;
            const matchStatus = statusFilter === "All" || item.status === statusFilter;

            return matchSearch && matchType && matchStatus;
        });
    }, [rows, search, typeFilter, statusFilter]);

    const totalPages = Math.max(1, Math.ceil(filteredRows.length / rowsPerPage));
    const currentPage = Math.min(page, totalPages - 1);

    const paginatedRows = useMemo(() => {
        if (filteredRows.length === 0) {
            return [];
        }

        const start = currentPage * rowsPerPage;
        return filteredRows.slice(start, start + rowsPerPage);
    }, [filteredRows, currentPage]);

    const commentTypeOptions = useMemo(() => {
        const types = Array.from(
            new Set(rows.map((item) => item.commentType).filter(Boolean)),
        );

        return ["All", ...types];
    }, [rows]);

    const hasActiveFilters =
        search.trim() !== "" || typeFilter !== "All" || statusFilter !== "All";

    const emptyTitle = rows.length === 0 ? t.noData : t.noMatchingData;
    const emptyMessage =
        rows.length === 0 ? t.noDataMessage : t.noMatchingMessage;

    const pageNumberLabel = filteredRows.length === 0 ? 0 : currentPage + 1;

    const pendingCount = rows.filter((item) => item.status === "Pending").length;
    const reviewedCount = rows.filter((item) => item.status === "Reviewed").length;
    const resolvedCount = rows.filter((item) => item.status === "Resolved").length;

    const handleOpenActionMenu = (
        event: MouseEvent<HTMLButtonElement>,
        row: UserComment,
    ) => {
        setActionAnchorEl(event.currentTarget);
        actionRowRef.current = row;
    };

    const handleCloseActionMenu = () => {
        setActionAnchorEl(null);
        actionRowRef.current = null;
    };

    const handleClearFilters = () => {
        setSearch("");
        setTypeFilter("All");
        setStatusFilter("All");
        setPage(0);
    };

    const handleChangeStatus = (row: UserComment, status: CommentStatus) => {
        setRows((prev) =>
            prev.map((item) => (item.id === row.id ? { ...item, status } : item)),
        );
    };

    const handleDelete = () => {
        if (!deleteRow) return;

        setRows((prev) => prev.filter((item) => item.id !== deleteRow.id));
        setDeleteRow(null);
    };

    return (
        <Box
            sx={{
                minHeight: "100vh",
                bgcolor: isDark ? "#0F172A" : "#F6F8FC",
                px: { xs: 1, md: 3 },
                py: { xs: 2, md: 3 },
                fontFamily: isKhmer
                    ? '"Kantumruy Pro", Inter, Arial, sans-serif'
                    : "Inter, Arial, sans-serif",
            }}
        >
            <Box sx={{ mb: 3 }}>
                <Typography
                    component="h1"
                    variant="h4"
                    sx={{
                        fontWeight: 900,
                        color: isDark ? "#F8FAFC" : "#0F172A",
                    }}
                >
                    {t.title}
                </Typography>

                <Typography component="p" sx={{ color: "text.secondary", mt: 0.6 }}>
                    {t.subtitle}
                </Typography>
            </Box>

            <Box
                sx={{
                    display: "grid",
                    gridTemplateColumns: {
                        xs: "1fr",
                        sm: "repeat(2, 1fr)",
                        lg: "repeat(4, 1fr)",
                    },
                    gap: 2.5,
                    mb: 3,
                }}
            >
                <SummaryCard
                    title={t.totalComments}
                    value={rows.length}
                    subtitle={t.allUserComments}
                    color="#2563EB"
                    bg={isDark ? "rgba(37,99,235,0.18)" : "#EAF2FF"}
                />

                <SummaryCard
                    title={t.pending}
                    value={pendingCount}
                    subtitle={t.needReview}
                    color="#D97706"
                    bg={isDark ? "rgba(245,158,11,0.18)" : "#FFF7E6"}
                />

                <SummaryCard
                    title={t.reviewed}
                    value={reviewedCount}
                    subtitle={t.alreadyReviewed}
                    color="#2563EB"
                    bg={isDark ? "rgba(37,99,235,0.18)" : "#EAF2FF"}
                />

                <SummaryCard
                    title={t.resolved}
                    value={resolvedCount}
                    subtitle={t.issueResolved}
                    color="#15803D"
                    bg={isDark ? "rgba(34,197,94,0.18)" : "#EAFBF0"}
                />
            </Box>

            <Paper
                elevation={0}
                sx={{
                    borderRadius: "18px",
                    overflow: "hidden",
                    border: isDark
                        ? "1px solid rgba(148,163,184,0.18)"
                        : "1px solid #E5EAF2",
                    bgcolor: isDark ? "#111827" : "#FFFFFF",
                    boxShadow: isDark ? "none" : "0 18px 45px rgba(15,23,42,0.06)",
                }}
            >
                <Box
                    sx={{
                        display: "flex",
                        alignItems: "center",
                        gap: 2,
                        p: 2.5,
                        flexWrap: "wrap",
                    }}
                >
                    <TextField
                        placeholder={t.search}
                        value={search}
                        onChange={(event) => {
                            setSearch(event.target.value);
                            setPage(0);
                        }}
                        size="small"
                        slotProps={{
                            input: {
                                startAdornment: (
                                    <InputAdornment position="start">
                                        <SearchIcon fontSize="small" />
                                    </InputAdornment>
                                ),
                            },
                        }}
                        sx={{
                            width: {
                                xs: "100%",
                                sm: 280,
                            },
                            "& .MuiOutlinedInput-root": {
                                height: 44,
                                borderRadius: "14px",
                                bgcolor: isDark ? "rgba(15,23,42,0.7)" : "#FFFFFF",
                            },
                            "& input": {
                                fontSize: 14,
                            },
                        }}
                    />

                    <FormControl
                        size="small"
                        sx={{
                            width: {
                                xs: "100%",
                                sm: 190,
                            },
                        }}
                    >
                        <Select
                            value={typeFilter}
                            onChange={(event) => {
                                setTypeFilter(event.target.value);
                                setPage(0);
                            }}
                            sx={{
                                height: 44,
                                borderRadius: "14px",
                                bgcolor: isDark ? "rgba(15,23,42,0.7)" : "#FFFFFF",
                                "& .MuiSelect-select": {
                                    display: "flex",
                                    alignItems: "center",
                                    fontSize: 16,
                                    fontWeight: 700,
                                },
                            }}
                        >
                            {commentTypeOptions.map((type) => (
                                <MenuItem key={type} value={type}>
                                    {type === "All" ? t.allTypes : getCommentTypeLabel(type)}
                                </MenuItem>
                            ))}
                        </Select>
                    </FormControl>

                    <FormControl
                        size="small"
                        sx={{
                            width: {
                                xs: "100%",
                                sm: 170,
                            },
                        }}
                    >
                        <Select
                            value={statusFilter}
                            onChange={(event) => {
                                setStatusFilter(event.target.value as "All" | CommentStatus);
                                setPage(0);
                            }}
                            sx={{
                                height: 44,
                                borderRadius: "14px",
                                bgcolor: isDark ? "rgba(15,23,42,0.7)" : "#FFFFFF",
                                "& .MuiSelect-select": {
                                    display: "flex",
                                    alignItems: "center",
                                    fontSize: 16,
                                    fontWeight: 700,
                                },
                            }}
                        >
                            <MenuItem value="All">{t.allStatus}</MenuItem>
                            <MenuItem value="Pending">{getStatusLabel("Pending")}</MenuItem>
                            <MenuItem value="Reviewed">{getStatusLabel("Reviewed")}</MenuItem>
                            <MenuItem value="Resolved">{getStatusLabel("Resolved")}</MenuItem>
                        </Select>
                    </FormControl>
                </Box>

                <Divider />

                <Box
                    sx={{
                        width: "100%",
                        overflowX: {
                            xs: "auto",
                            xl: "hidden",
                        },
                    }}
                >
                    <Box
                        sx={{
                            minWidth: {
                                xs: 980,
                                xl: "100%",
                            },
                        }}
                    >
                        <Box
                            sx={{
                                display: "grid",
                                gridTemplateColumns: TABLE_COLUMNS,
                                alignItems: "center",
                                minHeight: 56,
                                bgcolor: isDark ? "rgba(30,41,59,0.8)" : "#F8FAFC",
                                borderBottom: isDark
                                    ? "1px solid rgba(148,163,184,0.18)"
                                    : "1px solid #E5EAF2",
                            }}
                        >
                            <HeaderCell>{t.no}</HeaderCell>
                            <HeaderCell>{t.user}</HeaderCell>
                            <HeaderCell>{t.commentType}</HeaderCell>
                            <HeaderCell>{t.commentMessage}</HeaderCell>
                            <HeaderCell>{t.status}</HeaderCell>
                            <HeaderCell>{t.createdDate}</HeaderCell>
                            <HeaderCell noBorder>{t.actions}</HeaderCell>
                        </Box>

                        <Box sx={{ minHeight: FIXED_BODY_HEIGHT }}>
                            {paginatedRows.map((row, index) => (
                                <Box
                                    key={row.id}
                                    sx={{
                                        display: "grid",
                                        gridTemplateColumns: TABLE_COLUMNS,
                                        alignItems: "center",
                                        height: ROW_HEIGHT,
                                        borderBottom: isDark
                                            ? "1px solid rgba(148,163,184,0.12)"
                                            : "1px solid #EEF2F7",
                                        "&:hover": {
                                            bgcolor: isDark
                                                ? "rgba(59,130,246,0.08)"
                                                : "#F8FBFF",
                                        },
                                    }}
                                >
                                    <BodyCell>{currentPage * rowsPerPage + index + 1}</BodyCell>

                                    <Box
                                        sx={{
                                            height: "100%",
                                            display: "flex",
                                            alignItems: "center",
                                            gap: "10px",
                                            minWidth: 0,
                                            px: 1.25,
                                            borderRight: columnBorder,
                                        }}
                                    >
                                        <Avatar
                                            src={row.avatar || undefined}
                                            alt={row.userName}
                                            sx={{
                                                width: 38,
                                                height: 38,
                                                bgcolor: isDark
                                                    ? "rgba(37,99,235,0.2)"
                                                    : "#EAF2FF",
                                                color: "#2563EB",
                                                fontWeight: 800,
                                                fontSize: 14,
                                                flexShrink: 0,
                                                border: isDark
                                                    ? "1px solid rgba(148,163,184,0.18)"
                                                    : "1px solid #E5EAF2",
                                            }}
                                        >
                                            {row.userName.charAt(0).toUpperCase()}
                                        </Avatar>

                                        <Box
                                            sx={{
                                                minWidth: 0,
                                                display: "flex",
                                                flexDirection: "column",
                                                justifyContent: "center",
                                                gap: 0.25,
                                                lineHeight: 1,
                                            }}
                                        >
                                            <Box
                                                sx={{
                                                    fontWeight: 800,
                                                    fontSize: 14,
                                                    lineHeight: "18px",
                                                    whiteSpace: "nowrap",
                                                    overflow: "hidden",
                                                    textOverflow: "ellipsis",
                                                }}
                                            >
                                                {row.userName}
                                            </Box>

                                            <Box
                                                sx={{
                                                    color: "text.secondary",
                                                    fontSize: 12,
                                                    lineHeight: "16px",
                                                    whiteSpace: "nowrap",
                                                    overflow: "hidden",
                                                    textOverflow: "ellipsis",
                                                }}
                                            >
                                                {row.email}
                                            </Box>
                                        </Box>
                                    </Box>

                                    <Box
                                        sx={{
                                            height: "100%",
                                            display: "flex",
                                            alignItems: "center",
                                            px: 1.25,
                                            borderRight: columnBorder,
                                        }}
                                    >
                                        <Chip
                                            label={getCommentTypeLabel(row.commentType)}
                                            size="small"
                                            sx={{
                                                fontWeight: 700,
                                                borderRadius: "8px",
                                                color: "#2563EB",
                                                bgcolor: isDark
                                                    ? "rgba(37,99,235,0.16)"
                                                    : "#EAF2FF",
                                            }}
                                        />
                                    </Box>

                                    <BodyCell>{getMessage(row)}</BodyCell>

                                    <Box
                                        sx={{
                                            height: "100%",
                                            display: "flex",
                                            alignItems: "center",
                                            px: 1.25,
                                            borderRight: columnBorder,
                                        }}
                                    >
                                        <StatusChip
                                            status={row.status}
                                            label={getStatusLabel(row.status)}
                                        />
                                    </Box>

                                    <BodyCell>{row.createdAt}</BodyCell>

                                    <Box
                                        sx={{
                                            height: "100%",
                                            width: "100%",
                                            display: "flex",
                                            alignItems: "center",
                                            justifyContent: "center",
                                            px: 0.75,
                                        }}
                                    >
                                        <IconButton
                                            size="small"
                                            title={t.actions}
                                            onClick={(event) => handleOpenActionMenu(event, row)}
                                            sx={{
                                                width: 34,
                                                height: 34,
                                                color: "text.secondary",
                                                borderRadius: "10px",
                                                "&:hover": {
                                                    color: "#2563EB",
                                                    bgcolor: isDark
                                                        ? "rgba(37,99,235,0.12)"
                                                        : "#EFF6FF",
                                                },
                                            }}
                                        >
                                            <MoreVerticalIcon sx={{ fontSize: 22 }} />
                                        </IconButton>
                                    </Box>
                                </Box>
                            ))}

                            {paginatedRows.length > 0 && paginatedRows.length < rowsPerPage ? (
                                <Box
                                    sx={{
                                        height: (rowsPerPage - paginatedRows.length) * ROW_HEIGHT,
                                        borderBottom: isDark
                                            ? "1px solid rgba(148,163,184,0.12)"
                                            : "1px solid #EEF2F7",
                                    }}
                                />
                            ) : null}

                            {paginatedRows.length === 0 ? (
                                <Box
                                    sx={{
                                        minHeight: FIXED_BODY_HEIGHT,
                                        display: "flex",
                                        alignItems: "center",
                                        justifyContent: "center",
                                        borderBottom: isDark
                                            ? "1px solid rgba(148,163,184,0.12)"
                                            : "1px solid #EEF2F7",
                                        px: 2,
                                        py: 5,
                                        textAlign: "center",
                                    }}
                                >
                                    <Box
                                        sx={{
                                            maxWidth: 360,
                                            display: "flex",
                                            flexDirection: "column",
                                            alignItems: "center",
                                            gap: 1.25,
                                        }}
                                    >
                                        <Box
                                            sx={{
                                                width: 58,
                                                height: 58,
                                                borderRadius: "18px",
                                                bgcolor: isDark
                                                    ? "rgba(37,99,235,0.14)"
                                                    : "#EAF2FF",
                                                color: "#2563EB",
                                                display: "flex",
                                                alignItems: "center",
                                                justifyContent: "center",
                                            }}
                                        >
                                            <CommentIcon />
                                        </Box>

                                        <Typography
                                            component="p"
                                            sx={{
                                                fontWeight: 900,
                                                fontSize: 18,
                                                color: isDark ? "#F8FAFC" : "#0F172A",
                                            }}
                                        >
                                            {emptyTitle}
                                        </Typography>

                                        <Typography
                                            component="p"
                                            sx={{ color: "text.secondary", fontSize: 14 }}
                                        >
                                            {emptyMessage}
                                        </Typography>

                                        {hasActiveFilters ? (
                                            <Button
                                                onClick={handleClearFilters}
                                                variant="outlined"
                                                sx={{
                                                    mt: 1,
                                                    borderRadius: "12px",
                                                    textTransform: "none",
                                                    fontWeight: 800,
                                                }}
                                            >
                                                {t.clearFilters}
                                            </Button>
                                        ) : null}
                                    </Box>
                                </Box>
                            ) : null}
                        </Box>
                    </Box>
                </Box>

                <Divider />

                <Box
                    sx={{
                        px: { xs: 1.5, sm: 2.5 },
                        pt: 2,
                        pb: 2,
                        bgcolor: isDark ? "#111827" : "#FFFFFF",
                    }}
                >
                    <Box
                        sx={{
                            minHeight: 50,
                            display: "grid",
                            gridTemplateColumns: "1fr auto 1fr",
                            alignItems: "center",
                            gap: 2,
                        }}
                    >
                        <Button
                            disabled={filteredRows.length === 0 || currentPage === 0}
                            onClick={() => setPage((prev) => Math.max(prev - 1, 0))}
                            startIcon={<ChevronLeftIcon sx={{ fontSize: 16 }} />}
                            sx={{
                                justifySelf: "start",
                                height: 38,
                                px: 1.8,
                                minWidth: 106,
                                borderRadius: "10px",
                                textTransform: "none",
                                fontWeight: 800,
                                fontSize: 13,
                                color: isDark ? "#CBD5E1" : "#6B7280",
                                border: isDark
                                    ? "1px solid rgba(148,163,184,0.18)"
                                    : "1px solid #E5E7EB",
                                bgcolor: isDark ? "rgba(15,23,42,0.65)" : "#FFFFFF",
                                boxShadow: "none",
                            }}
                        >
                            {t.previous}
                        </Button>

                        <Box
                            sx={{
                                width: 44,
                                height: 44,
                                borderRadius: "12px",
                                display: "flex",
                                alignItems: "center",
                                justifyContent: "center",
                                fontSize: 15,
                                fontWeight: 900,
                                color: isDark ? "#F8FAFC" : "#111827",
                                bgcolor: isDark ? "rgba(15,23,42,0.65)" : "#F9FAFB",
                                border: isDark
                                    ? "1px solid rgba(148,163,184,0.14)"
                                    : "1px solid #F1F3F6",
                            }}
                        >
                            {pageNumberLabel}
                        </Box>

                        <Button
                            disabled={filteredRows.length === 0 || currentPage >= totalPages - 1}
                            onClick={() =>
                                setPage((prev) => Math.min(prev + 1, totalPages - 1))
                            }
                            endIcon={<ChevronRightIcon sx={{ fontSize: 16 }} />}
                            sx={{
                                justifySelf: "end",
                                height: 38,
                                px: 1.8,
                                minWidth: 86,
                                borderRadius: "10px",
                                textTransform: "none",
                                fontWeight: 800,
                                fontSize: 13,
                                color: isDark ? "#CBD5E1" : "#6B7280",
                                border: isDark
                                    ? "1px solid rgba(148,163,184,0.18)"
                                    : "1px solid #E5E7EB",
                                bgcolor: isDark ? "rgba(15,23,42,0.65)" : "#FFFFFF",
                                boxShadow: "none",
                            }}
                        >
                            {t.next}
                        </Button>
                    </Box>
                </Box>
            </Paper>

            <Menu
                anchorEl={actionAnchorEl}
                open={Boolean(actionAnchorEl)}
                onClose={handleCloseActionMenu}
                anchorOrigin={{
                    vertical: "bottom",
                    horizontal: "right",
                }}
                transformOrigin={{
                    vertical: "top",
                    horizontal: "right",
                }}
                slotProps={{
                    paper: {
                        sx: {
                            mt: 1,
                            minWidth: 230,
                            borderRadius: "16px",
                            overflow: "hidden",
                            p: 1,
                            boxShadow: isDark
                                ? "0 20px 45px rgba(0,0,0,0.45)"
                                : "0 20px 45px rgba(15,23,42,0.16)",
                            border: isDark
                                ? "1px solid rgba(148,163,184,0.18)"
                                : "1px solid #E5EAF2",
                            bgcolor: isDark ? "#111827" : "#FFFFFF",
                        },
                    },
                }}
            >
                <MenuItem
                    onClick={() => {
                        const actionRow = actionRowRef.current;
                        if (actionRow) setViewRow(actionRow);
                        handleCloseActionMenu();
                    }}
                    sx={{
                        minHeight: 50,
                        gap: 1.6,
                        borderRadius: "12px",
                        fontSize: 15,
                        fontWeight: 700,
                    }}
                >
                    <EditIcon sx={{ fontSize: 25 }} />
                    {t.editComment}
                </MenuItem>

                <MenuItem
                    onClick={() => {
                        const actionRow = actionRowRef.current;
                        if (actionRow) setViewRow(actionRow);
                        handleCloseActionMenu();
                    }}
                    sx={{
                        minHeight: 50,
                        gap: 1.6,
                        borderRadius: "12px",
                        fontSize: 15,
                        fontWeight: 700,
                    }}
                >
                    <HistoryIcon sx={{ fontSize: 25 }} />
                    {t.viewHistory}
                </MenuItem>

                <MenuItem
                    onClick={() => {
                        const actionRow = actionRowRef.current;
                        if (actionRow) {
                            handleChangeStatus(
                                actionRow,
                                actionRow.status === "Resolved" ? "Pending" : "Resolved",
                            );
                        }

                        handleCloseActionMenu();
                    }}
                    sx={{
                        minHeight: 50,
                        gap: 1.6,
                        borderRadius: "12px",
                        fontSize: 15,
                        fontWeight: 700,
                    }}
                >
                    <ToggleIcon sx={{ fontSize: 26 }} />
                    {t.toggleStatus}
                </MenuItem>

                <MenuItem
                    onClick={() => {
                        const actionRow = actionRowRef.current;
                        if (actionRow) setDeleteRow(actionRow);
                        handleCloseActionMenu();
                    }}
                    sx={{
                        minHeight: 50,
                        gap: 1.6,
                        borderRadius: "12px",
                        fontSize: 15,
                        fontWeight: 800,
                        color: "#DC2626",
                    }}
                >
                    <DeleteIcon sx={{ fontSize: 25 }} />
                    {t.deleteComment}
                </MenuItem>
            </Menu>

            <Dialog
                open={Boolean(viewRow)}
                onClose={() => setViewRow(null)}
                fullWidth
                maxWidth="sm"
                slotProps={{
                    paper: {
                        sx: {
                            borderRadius: "18px",
                        },
                    },
                }}
            >
                <DialogTitle
                    sx={{
                        fontWeight: 900,
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                    }}
                >
                    {t.commentDetail}

                    <IconButton onClick={() => setViewRow(null)}>
                        <CloseIcon />
                    </IconButton>
                </DialogTitle>

                <DialogContent>
                    {viewRow ? (
                        <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
                            <InfoRow label={t.userName} value={viewRow.userName} />
                            <InfoRow label={t.email} value={viewRow.email} />
                            <InfoRow
                                label={t.commentType}
                                value={getCommentTypeLabel(viewRow.commentType)}
                            />
                            <InfoRow
                                label={t.status}
                                value={getStatusLabel(viewRow.status)}
                            />
                            <InfoRow label={t.createdDate} value={viewRow.createdAt} />

                            <Box>
                                <Typography component="p" sx={{ fontWeight: 900, mb: 0.75 }}>
                                    {t.message}
                                </Typography>

                                <Box
                                    sx={{
                                        p: 2,
                                        borderRadius: "14px",
                                        bgcolor: isDark ? "rgba(15,23,42,0.8)" : "#F8FAFC",
                                        border: isDark
                                            ? "1px solid rgba(148,163,184,0.18)"
                                            : "1px solid #E5EAF2",
                                        color: "text.secondary",
                                    }}
                                >
                                    {getMessage(viewRow)}
                                </Box>
                            </Box>
                        </Box>
                    ) : null}
                </DialogContent>

                <DialogActions sx={{ p: 3, pt: 1 }}>
                    <Button
                        onClick={() => setViewRow(null)}
                        variant="outlined"
                        sx={{
                            borderRadius: "12px",
                            textTransform: "none",
                            fontWeight: 700,
                        }}
                    >
                        {t.close}
                    </Button>

                    {viewRow ? (
                        <Button
                            onClick={() => {
                                handleChangeStatus(viewRow, "Resolved");
                                setViewRow(null);
                            }}
                            variant="contained"
                            sx={{
                                borderRadius: "12px",
                                textTransform: "none",
                                fontWeight: 700,
                                bgcolor: "#15803D",
                                "&:hover": {
                                    bgcolor: "#166534",
                                },
                            }}
                        >
                            {t.markResolved}
                        </Button>
                    ) : null}
                </DialogActions>
            </Dialog>

            <Dialog
                open={Boolean(deleteRow)}
                onClose={() => setDeleteRow(null)}
                fullWidth
                maxWidth="xs"
                slotProps={{
                    paper: {
                        sx: {
                            borderRadius: "18px",
                        },
                    },
                }}
            >
                <DialogTitle sx={{ fontWeight: 900 }}>{t.deleteTitle}</DialogTitle>

                <DialogContent>
                    <Typography component="p" sx={{ color: "text.secondary" }}>
                        {t.deleteBefore}{" "}
                        <Box component="strong">{deleteRow?.userName}</Box>?
                    </Typography>
                </DialogContent>

                <DialogActions sx={{ p: 3, pt: 1 }}>
                    <Button
                        onClick={() => setDeleteRow(null)}
                        variant="outlined"
                        sx={{
                            borderRadius: "12px",
                            textTransform: "none",
                            fontWeight: 700,
                        }}
                    >
                        {t.cancel}
                    </Button>

                    <Button
                        onClick={handleDelete}
                        variant="contained"
                        color="error"
                        sx={{
                            borderRadius: "12px",
                            textTransform: "none",
                            fontWeight: 700,
                        }}
                    >
                        {t.delete}
                    </Button>
                </DialogActions>
            </Dialog>
        </Box>
    );
}

function HeaderCell({
    children,
    noBorder = false,
}: {
    children: string;
    noBorder?: boolean;
}) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";

    return (
        <Box
            sx={{
                height: "100%",
                display: "flex",
                alignItems: "center",
                px: 1.25,
                fontWeight: 900,
                fontSize: 14,
                color: "text.primary",
                whiteSpace: "nowrap",
                borderRight: noBorder
                    ? "none"
                    : isDark
                      ? "1px solid rgba(148,163,184,0.18)"
                      : "1px solid #E5EAF2",
            }}
        >
            {children}
        </Box>
    );
}

function BodyCell({
    children,
    noBorder = false,
}: {
    children: string | number;
    noBorder?: boolean;
}) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";

    return (
        <Box
            sx={{
                height: "100%",
                display: "flex",
                alignItems: "center",
                px: 1.25,
                color: "text.secondary",
                fontSize: 14,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
                minWidth: 0,
                borderRight: noBorder
                    ? "none"
                    : isDark
                      ? "1px solid rgba(148,163,184,0.14)"
                      : "1px solid #E5EAF2",
            }}
        >
            {children}
        </Box>
    );
}

function StatusChip({
    status,
    label,
}: {
    status: CommentStatus;
    label: string;
}) {
    return (
        <Chip
            label={label}
            size="small"
            sx={{
                fontWeight: 800,
                borderRadius: "8px",
                color:
                    status === "Pending"
                        ? "#D97706"
                        : status === "Reviewed"
                          ? "#2563EB"
                          : "#15803D",
                bgcolor:
                    status === "Pending"
                        ? "rgba(245,158,11,0.14)"
                        : status === "Reviewed"
                          ? "rgba(37,99,235,0.14)"
                          : "rgba(34,197,94,0.14)",
            }}
        />
    );
}

function SummaryCard({
    title,
    value,
    subtitle,
    color,
    bg,
}: {
    title: string;
    value: number;
    subtitle: string;
    color: string;
    bg: string;
}) {
    const theme = useTheme();
    const isDark = theme.palette.mode === "dark";

    return (
        <Card
            elevation={0}
            sx={{
                borderRadius: "18px",
                border: isDark
                    ? "1px solid rgba(148,163,184,0.18)"
                    : "1px solid #E5EAF2",
                bgcolor: isDark ? "#111827" : "#FFFFFF",
                boxShadow: isDark ? "none" : "0 16px 38px rgba(15,23,42,0.06)",
            }}
        >
            <CardContent>
                <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
                    <Box
                        sx={{
                            width: 64,
                            height: 64,
                            borderRadius: "18px",
                            bgcolor: bg,
                            color,
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            flexShrink: 0,
                        }}
                    >
                        <CommentIcon />
                    </Box>

                    <Box>
                        <Typography
                            component="p"
                            sx={{ color: "text.secondary", fontWeight: 800 }}
                        >
                            {title}
                        </Typography>

                        <Typography
                            component="p"
                            variant="h4"
                            sx={{
                                fontWeight: 900,
                                lineHeight: 1.2,
                            }}
                        >
                            {value}
                        </Typography>

                        <Typography component="p" sx={{ color: "text.secondary", fontSize: 13 }}>
                            {subtitle}
                        </Typography>
                    </Box>
                </Box>
            </CardContent>
        </Card>
    );
}

function InfoRow({ label, value }: { label: string; value: string }) {
    return (
        <Box
            sx={{
                display: "grid",
                gridTemplateColumns: {
                    xs: "1fr",
                    sm: "160px 1fr",
                },
                gap: 1,
            }}
        >
            <Typography component="p" sx={{ fontWeight: 900 }}>
                {label}
            </Typography>

            <Typography component="p" sx={{ color: "text.secondary" }}>
                {value}
            </Typography>
        </Box>
    );
}

function CommentIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M7 8h10M7 12h7M21 12c0 4.4-4 8-9 8-1.2 0-2.3-.2-3.3-.6L3 21l1.8-4.5C3.7 15.2 3 13.7 3 12c0-4.4 4-8 9-8s9 3.6 9 8Z"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.8"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
        </SvgIcon>
    );
}

function SearchIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M11 19a8 8 0 1 1 5.7-2.4L21 21"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
        </SvgIcon>
    );
}

function MoreVerticalIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M12 8h.01M12 12h.01M12 16h.01"
                fill="none"
                stroke="currentColor"
                strokeWidth="3"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
        </SvgIcon>
    );
}

function EditIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M4 20h4l10.5-10.5a2.1 2.1 0 0 0-3-3L5 17v3Z"
                fill="currentColor"
            />
            <path
                d="M13.5 7.5l3 3"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
            />
        </SvgIcon>
    );
}

function HistoryIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M3 12a9 9 0 1 0 3-6.7"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
            />
            <path
                d="M3 4v5h5"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
            <path
                d="M12 7v5l3 2"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
        </SvgIcon>
    );
}

function ToggleIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M7 7h10a5 5 0 0 1 0 10H7A5 5 0 0 1 7 7Z"
                fill="currentColor"
            />
            <circle cx="8" cy="12" r="3" fill="white" />
        </SvgIcon>
    );
}

function DeleteIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
        </SvgIcon>
    );
}

function ChevronLeftIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M15 6L9 12L15 18"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
        </SvgIcon>
    );
}

function ChevronRightIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M9 6L15 12L9 18"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
            />
        </SvgIcon>
    );
}

function CloseIcon(props: ComponentProps<typeof SvgIcon>) {
    return (
        <SvgIcon {...props}>
            <path
                d="M6 6l12 12M18 6L6 18"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
            />
        </SvgIcon>
    );
}
