"use client";

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

import MoreVertIcon from "@mui/icons-material/MoreVert";
import Box from "@mui/material/Box";
import CircularProgress from "@mui/material/CircularProgress";
import IconButton from "@mui/material/IconButton";
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 type { SxProps, Theme } from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import {
  DataTable,
  type DataTableColDef,
} from "@/components/ui/data-table";
import {
  CalendarAddNewIcon,
  PencilEditIcon,
  SetDeadlineIcon,
} from "@/components/ui/icon";
import { formatDate } from "@/lib/date-utils";

import type { ProgressReportScheduleRow } from "../../progress-report-schedule-data";
import {
  normalizeProgressReportLanguage,
  translateProgressReportValue,
  type ProgressReportDetailLabels,
} from "../../progress-report-i18n";
import { ProgressReportStatusCell } from "../table/progress-report-table-cells";

const HEADER_HEIGHT = 45;
const ROW_HEIGHT = 60;

type ProgressReportMeetingsDeadlinesTableProps = {
  rows: ProgressReportScheduleRow[];
  labels: ProgressReportDetailLabels;
  loadingActionRowId?: string | null;
  onAction: (row: ProgressReportScheduleRow) => void;
};

function resolveName(
  row: ProgressReportScheduleRow,
  labels: ProgressReportDetailLabels,
): string {
  switch (row.nameKey) {
    case "firstMeeting":
      return labels.firstMeeting;
    case "secondMeeting":
      return labels.secondMeeting;
    case "deadline":
      return labels.deadline;
    case "firstDeadline":
      return labels.firstDeadline;
    case "secondDeadline":
      return labels.secondDeadline;
  }
}

function ScheduleActionsMenu({
  row,
  labels,
  onAction,
}: {
  row: ProgressReportScheduleRow;
  labels: ProgressReportDetailLabels;
  onAction: (row: ProgressReportScheduleRow) => void;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const menuOpen = Boolean(anchorEl);
  const isEdit = row.action === "edit";
  const isBlocked = row.action === "blocked";
  const actionLabel = isEdit
    ? row.type === "meeting"
      ? labels.scheduleActions.editMeeting
      : labels.scheduleActions.editDeadline
    : row.type === "meeting"
      ? labels.scheduleActions.addMeeting
      : labels.scheduleActions.setDeadline;

  function openMenu(event: MouseEvent<HTMLElement>) {
    setAnchorEl(event.currentTarget);
  }

  function closeMenu() {
    setAnchorEl(null);
  }

  function runAction() {
    closeMenu();
    onAction(row);
  }

  const iconSx = {
    fontSize: 20,
    color: isDark ? alpha("#ffffff", 0.72) : "#717680",
  } as const;

  return (
    <>
      <IconButton
        size="small"
        aria-label={labels.scheduleActions.openActions}
        aria-haspopup="menu"
        aria-expanded={menuOpen ? "true" : undefined}
        onClick={openMenu}
        sx={{ color: "text.secondary" }}
      >
        <MoreVertIcon sx={{ fontSize: 22 }} />
      </IconButton>

      <Menu
        anchorEl={anchorEl}
        open={menuOpen}
        onClose={closeMenu}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              mt: 0.5,
              minWidth: 220,
              borderRadius: "12px",
              border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#f5f5f5"}`,
              bgcolor: isDark ? "#101828" : "#ffffff",
              boxShadow: isDark
                ? "0 12px 30px rgba(0, 0, 0, 0.5)"
                : "0px 0px 10.6px rgba(0, 0, 0, 0.1)",
            },
          },
        }}
      >
        <MenuItem
          disabled={isBlocked}
          onClick={runAction}
          title={isBlocked ? labels.scheduleActions.blocked : actionLabel}
          sx={{
            minHeight: 44,
            px: 2,
            gap: 1.5,
            color: isDark ? alpha("#ffffff", 0.86) : "#414651",
            fontSize: 13,
            fontWeight: 500,
          }}
        >
          {isEdit ? (
            <PencilEditIcon sx={iconSx} />
          ) : row.type === "meeting" ? (
            <CalendarAddNewIcon sx={iconSx} />
          ) : (
            <SetDeadlineIcon sx={iconSx} />
          )}
          <Box>
            <Typography sx={{ fontSize: 13, fontWeight: 500 }}>
              {actionLabel}
            </Typography>
            {isBlocked ? (
              <Typography sx={{ mt: 0.25, fontSize: 11, color: "text.disabled" }}>
                {labels.scheduleActions.blocked}
              </Typography>
            ) : null}
          </Box>
        </MenuItem>
      </Menu>
    </>
  );
}

export function ProgressReportMeetingsDeadlinesTable({
  rows,
  labels,
  loadingActionRowId,
  onAction,
}: ProgressReportMeetingsDeadlinesTableProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const { language } = useAppLanguage();
  const pageLanguage = normalizeProgressReportLanguage(language);

  const columns = useMemo<DataTableColDef<ProgressReportScheduleRow>[]>(
    () => [
      {
        field: "type",
        headerName: labels.scheduleColumns.type,
        flex: 0.8,
        minWidth: 120,
        sortable: false,
        filterable: false,
        disableColumnMenu: true,
        renderCell: (params) => (
          <Typography sx={{ fontSize: 13, fontWeight: 500 }}>
            {params.row.type === "meeting"
              ? labels.scheduleTypeMeeting
              : labels.scheduleTypeDeadline}
          </Typography>
        ),
      },
      {
        field: "nameKey",
        headerName: labels.scheduleColumns.name,
        flex: 1.2,
        minWidth: 160,
        sortable: false,
        filterable: false,
        disableColumnMenu: true,
        valueGetter: (_value, row) => resolveName(row, labels),
        renderCell: (params) => (
          <Typography sx={{ fontSize: 13, fontWeight: 500 }} noWrap>
            {resolveName(params.row, labels)}
          </Typography>
        ),
      },
      {
        field: "date",
        headerName: labels.scheduleColumns.date,
        flex: 1,
        minWidth: 140,
        sortable: false,
        filterable: false,
        disableColumnMenu: true,
        renderCell: (params) => (
          <Typography sx={{ fontSize: 13, fontWeight: 500 }}>
            {params.row.date === "-"
              ? "-"
              : formatDate(params.row.date, language)}
          </Typography>
        ),
      },
      {
        field: "status",
        headerName: labels.scheduleColumns.status,
        flex: 0.8,
        minWidth: 120,
        sortable: false,
        filterable: false,
        disableColumnMenu: true,
        renderCell: (params) =>
          params.row.status === "-" ? (
            <Typography sx={{ fontSize: 13 }}>-</Typography>
          ) : (
            <ProgressReportStatusCell
              status={params.row.status}
              label={translateProgressReportValue(
                params.row.status,
                pageLanguage,
              )}
            />
          ),
      },
      {
        field: "action",
        headerName: labels.scheduleColumns.action,
        flex: 0.55,
        minWidth: 90,
        sortable: false,
        filterable: false,
        disableColumnMenu: true,
        align: "center",
        headerAlign: "center",
        renderCell: (params) => {
          const row = params.row;

          if (loadingActionRowId === row.id) {
            return <CircularProgress size={20} />;
          }

          if (row.action === "locked") {
            return <Typography sx={{ fontSize: 13 }}>-</Typography>;
          }

          return (
            <ScheduleActionsMenu
              row={row}
              labels={labels}
              onAction={onAction}
            />
          );
        },
      },
    ],
    [
      labels,
      language,
      loadingActionRowId,
      onAction,
      pageLanguage,
    ],
  );

  const tableHeight = HEADER_HEIGHT + rows.length * ROW_HEIGHT;

  const dataGridSx = useMemo<SxProps<Theme>>(() => {
    const headerBackground = isDark ? alpha("#ffffff", 0.06) : "#ddedfb";
    const bodyBackground = isDark ? "#101828" : "#ffffff";
    const borderColor = isDark ? alpha("#ffffff", 0.08) : "#f5f5f5";

    return {
      border: "none",
      "& .MuiDataGrid-columnHeaders": {
        bgcolor: headerBackground,
        borderBottom: `1px solid ${borderColor}`,
      },
      "& .MuiDataGrid-columnHeader": { px: 2, bgcolor: headerBackground },
      "& .MuiDataGrid-columnHeaderTitle": {
        fontSize: 12,
        fontWeight: 400,
        color: isDark ? alpha("#ffffff", 0.72) : "#717680",
      },
      "& .MuiDataGrid-cell": {
        px: 2,
        py: 0,
        bgcolor: bodyBackground,
        borderColor,
        color: isDark ? alpha("#ffffff", 0.86) : "#181d27",
      },
      "& .MuiDataGrid-row": { bgcolor: bodyBackground },
      "& .MuiDataGrid-row:hover": {
        bgcolor: isDark ? alpha("#ffffff", 0.04) : "#f9fafb",
      },
      "& .MuiDataGrid-withBorderColor": { borderColor },
    };
  }, [isDark]);

  return (
    <Box sx={{ width: "100%", minWidth: 0 }}>
      <DataTable
        rows={rows}
        columns={columns}
        getRowId={(row) => row.id}
        height={tableHeight}
        hidePagination
        rowHeight={ROW_HEIGHT}
        columnHeaderHeight={HEADER_HEIGHT}
        dataGridSx={dataGridSx}
        paperSx={{
          width: "100%",
          minWidth: 0,
          overflowX: "auto",
          overflowY: "hidden",
          borderRadius: "12px 12px 0 0",
          border: `1px solid ${isDark ? alpha("#ffffff", 0.1) : "#e9eaeb"}`,
        }}
      />
    </Box>
  );
}
