import {
    Avatar,
    Box,
    Button,
    Chip,
    Divider,
    IconButton,
    Paper,
    Typography,
    useTheme,
} from "@mui/material";
import type { MouseEvent } from "react";

import {
    FIXED_BODY_HEIGHT,
    ROW_HEIGHT,
    ROWS_PER_PAGE,
    TABLE_COLUMNS,
    type CommentTypesText,
} from "../constants/comment-types-constants";
import type { CommentStatus, UserComment } from "../types/comment-types-types";
import {
    ChevronLeftIcon,
    ChevronRightIcon,
    CommentIcon,
    MoreVerticalIcon,
} from "./comment-types-icons";
import { CommentFilterSection } from "./comment-filter-section";

type Props = {
    text: CommentTypesText;
    isDark: boolean;
    rows: UserComment[];
    page: number;
    totalPages: number;
    totalFilteredRows: number;
    search: string;
    typeFilter: string;
    statusFilter: "All" | CommentStatus;
    typeOptions: string[];
    hasActiveFilters: boolean;
    emptyTitle: string;
    emptyMessage: string;
    getTypeLabel: (value: string) => string;
    getStatusLabel: (value: CommentStatus) => string;
    getMessage: (row: UserComment) => string;
    onSearchChange: (value: string) => void;
    onTypeChange: (value: string) => void;
    onStatusChange: (value: "All" | CommentStatus) => void;
    onClearFilters: () => void;
    onPageChange: (page: number) => void;
    onOpenActionMenu: (event: MouseEvent<HTMLButtonElement>, row: UserComment) => void;
};

export function CommentTableSection(props: Props) {
    const {
        text,
        isDark,
        rows,
        page,
        totalPages,
        totalFilteredRows,
        search,
        typeFilter,
        statusFilter,
        typeOptions,
        hasActiveFilters,
        emptyTitle,
        emptyMessage,
        getTypeLabel,
        getStatusLabel,
        getMessage,
        onSearchChange,
        onTypeChange,
        onStatusChange,
        onClearFilters,
        onPageChange,
        onOpenActionMenu,
    } = props;

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

    return (
        <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",
            }}
        >
            <CommentFilterSection
                text={text}
                isDark={isDark}
                search={search}
                typeFilter={typeFilter}
                statusFilter={statusFilter}
                typeOptions={typeOptions}
                getTypeLabel={getTypeLabel}
                getStatusLabel={getStatusLabel}
                onSearchChange={onSearchChange}
                onTypeChange={onTypeChange}
                onStatusChange={onStatusChange}
            />

            <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: columnBorder,
                        }}
                    >
                        <HeaderCell>{text.no}</HeaderCell>
                        <HeaderCell>{text.user}</HeaderCell>
                        <HeaderCell>{text.commentType}</HeaderCell>
                        <HeaderCell>{text.commentMessage}</HeaderCell>
                        <HeaderCell>{text.status}</HeaderCell>
                        <HeaderCell>{text.createdDate}</HeaderCell>
                        <HeaderCell noBorder>{text.actions}</HeaderCell>
                    </Box>

                    <Box sx={{ minHeight: FIXED_BODY_HEIGHT }}>
                        {rows.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",
                                }}
                            >
                                <BodyCell>{page * ROWS_PER_PAGE + index + 1}</BodyCell>

                                <Box sx={{ height: "100%", display: "flex", alignItems: "center", gap: 1.25, 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,
                                        }}
                                    >
                                        {row.userName.charAt(0).toUpperCase()}
                                    </Avatar>
                                    <Box sx={{ minWidth: 0 }}>
                                        <Typography noWrap sx={{ fontWeight: 800, fontSize: 14 }}>{row.userName}</Typography>
                                        <Typography noWrap sx={{ color: "text.secondary", fontSize: 12 }}>{row.email}</Typography>
                                    </Box>
                                </Box>

                                <Box sx={{ height: "100%", display: "flex", alignItems: "center", px: 1.25, borderRight: columnBorder }}>
                                    <Chip
                                        label={getTypeLabel(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%", display: "flex", alignItems: "center", justifyContent: "center" }}>
                                    <IconButton size="small" title={text.actions} onClick={(event) => onOpenActionMenu(event, row)}>
                                        <MoreVerticalIcon sx={{ fontSize: 22 }} />
                                    </IconButton>
                                </Box>
                            </Box>
                        ))}

                        {rows.length > 0 && rows.length < ROWS_PER_PAGE ? (
                            <Box sx={{ height: (ROWS_PER_PAGE - rows.length) * ROW_HEIGHT }} />
                        ) : null}

                        {rows.length === 0 ? (
                            <Box sx={{ minHeight: FIXED_BODY_HEIGHT, display: "flex", alignItems: "center", justifyContent: "center", px: 2, 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 sx={{ fontWeight: 900, fontSize: 18 }}>{emptyTitle}</Typography>
                                    <Typography sx={{ color: "text.secondary", fontSize: 14 }}>{emptyMessage}</Typography>
                                    {hasActiveFilters ? (
                                        <Button onClick={onClearFilters} variant="outlined" sx={{ mt: 1, borderRadius: "12px", textTransform: "none", fontWeight: 800 }}>
                                            {text.clearFilters}
                                        </Button>
                                    ) : null}
                                </Box>
                            </Box>
                        ) : null}
                    </Box>
                </Box>
            </Box>

            <Divider />

            <Box sx={{ px: { xs: 1.5, sm: 2.5 }, py: 2 }}>
                <Box sx={{ minHeight: 50, display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center", gap: 2 }}>
                    <Button
                        disabled={totalFilteredRows === 0 || page === 0}
                        onClick={() => onPageChange(Math.max(page - 1, 0))}
                        startIcon={<ChevronLeftIcon sx={{ fontSize: 16 }} />}
                        sx={{ justifySelf: "start", textTransform: "none", fontWeight: 800 }}
                    >
                        {text.previous}
                    </Button>

                    <Box sx={{ width: 44, height: 44, borderRadius: "12px", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 900, bgcolor: isDark ? "rgba(15,23,42,0.65)" : "#F9FAFB" }}>
                        {totalFilteredRows === 0 ? 0 : page + 1}
                    </Box>

                    <Button
                        disabled={totalFilteredRows === 0 || page >= totalPages - 1}
                        onClick={() => onPageChange(Math.min(page + 1, totalPages - 1))}
                        endIcon={<ChevronRightIcon sx={{ fontSize: 16 }} />}
                        sx={{ justifySelf: "end", textTransform: "none", fontWeight: 800 }}
                    >
                        {text.next}
                    </Button>
                </Box>
            </Box>
        </Paper>
    );
}

function HeaderCell({ children, noBorder = false }: { children: string; noBorder?: boolean }) {
    const isDark = useTheme().palette.mode === "dark";
    return (
        <Box sx={{ height: "100%", display: "flex", alignItems: "center", px: 1.25, fontWeight: 900, fontSize: 14, whiteSpace: "nowrap", borderRight: noBorder ? "none" : isDark ? "1px solid rgba(148,163,184,0.18)" : "1px solid #E5EAF2" }}>
            {children}
        </Box>
    );
}

function BodyCell({ children }: { children: string | number }) {
    const isDark = useTheme().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", borderRight: 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)",
            }}
        />
    );
}
