"use client";

import dynamic from "next/dynamic";
import { useMemo, type ReactElement } from "react";

import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";
import type { SxProps, Theme } from "@mui/material/styles";
import type {
  DataGridProps,
  GridColDef,
  GridRenderCellParams,
  GridRowIdGetter,
  GridValidRowModel,
} from "@mui/x-data-grid";

import { DataTableCellTooltip } from "@/components/ui/data-table/data-table-tooltip-cell";
import type { DataTableColDef } from "@/components/ui/data-table/data-table-types";

const MuiDataGrid = dynamic(
  () => import("@mui/x-data-grid").then((mod) => mod.DataGrid),
  { ssr: false },
) as <Row extends GridValidRowModel>(
  props: DataGridProps<Row>,
) => ReactElement;

function mergeSx(base: SxProps<Theme>, custom?: SxProps<Theme>): SxProps<Theme> {
  if (!custom) return base;
  return [base, ...(Array.isArray(custom) ? custom : [custom])] as SxProps<Theme>;
}

function getCellTooltipTitle<Row extends GridValidRowModel>(
  params: GridRenderCellParams<Row>,
  showTooltip: NonNullable<DataTableColDef<Row>["showTooltip"]>,
) {
  if (typeof showTooltip === "function") {
    return showTooltip(params) ?? null;
  }

  const value = params.formattedValue ?? params.value;
  if (value == null || value === "") return null;
  return String(value);
}

function applyColumnTooltips<Row extends GridValidRowModel>(
  columns: DataTableColDef<Row>[],
): GridColDef<Row>[] {
  return columns.map((column) => {
    const { showTooltip, headerTooltip, ...gridColumn } = column;
    let nextColumn: GridColDef<Row> = {
      ...gridColumn,
      headerAlign: "center",
    };

    if (showTooltip) {
      const originalRenderCell = column.renderCell;
      nextColumn = {
        ...nextColumn,
        renderCell: (params) => {
          const content = originalRenderCell
            ? originalRenderCell(params)
            : (params.formattedValue ?? params.value);
          const title = getCellTooltipTitle(params, showTooltip);

          return (
            <DataTableCellTooltip title={title ?? undefined}>
              {content}
            </DataTableCellTooltip>
          );
        },
      };
    }

    if (headerTooltip) {
      const originalRenderHeader = column.renderHeader;
      nextColumn = {
        ...nextColumn,
        renderHeader: (params) => {
          const content = originalRenderHeader
            ? originalRenderHeader(params)
            : params.colDef.headerName;

          return (
            <DataTableCellTooltip title={headerTooltip}>
              <Box component="span" sx={{ display: "inline-block", width: "100%" }}>
                {content}
              </Box>
            </DataTableCellTooltip>
          );
        },
      };
    }

    return nextColumn;
  });
}

type Props<Row extends GridValidRowModel> = {
  rows: Row[];
  columns: DataTableColDef<Row>[];
  getRowId?: GridRowIdGetter<Row>;
  emptyMessage?: string;
  height: number;
  rowHeight: number;
  columnHeaderHeight: number;
  paperSx?: SxProps<Theme>;
  dataGridSx?: SxProps<Theme>;
};

export function MeetingSummaryListOfIssueDataGrid<Row extends GridValidRowModel>({
  rows,
  columns,
  getRowId,
  emptyMessage = "No issues found.",
  height,
  rowHeight,
  columnHeaderHeight,
  paperSx,
  dataGridSx,
}: Props<Row>) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  const processedColumns = useMemo(
    () => applyColumnTooltips(columns),
    [columns],
  );

  const showEmptyMessage = rows.length === 0;

  return (
    <Paper
      elevation={0}
      sx={mergeSx(
        {
          borderRadius: "12px",
          border: `1px solid ${isDark ? alpha("#ffffff", 0.1) : "#e9eaeb"}`,
          overflow: "hidden",
          backgroundColor: isDark ? "#101828" : "#ffffff",
        },
        paperSx,
      )}
    >
      <Box sx={{ height, width: "100%", position: "relative" }}>
        {showEmptyMessage ? (
          <Box
            sx={{
              position: "absolute",
              inset: 0,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              px: 3,
              textAlign: "center",
              zIndex: 1,
            }}
          >
            <Typography sx={{ color: "text.secondary", fontSize: 13, fontWeight: 500 }}>
              {emptyMessage}
            </Typography>
          </Box>
        ) : null}

        <MuiDataGrid
          rows={rows}
          columns={processedColumns}
          getRowId={getRowId}
          hideFooter
          disableRowSelectionOnClick
          disableColumnFilter
          disableColumnSelector
          disableDensitySelector
          disableColumnMenu
          showCellVerticalBorder
          showColumnVerticalBorder
          rowHeight={rowHeight}
          columnHeaderHeight={columnHeaderHeight}
          sx={dataGridSx}
        />
      </Box>
    </Paper>
  );
}
