"use client";

import AutorenewOutlinedIcon from "@mui/icons-material/AutorenewOutlined";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import { alpha, useTheme } from "@mui/material/styles";
import type { SxProps, Theme } from "@mui/material/styles";

import { DataTableNumberCell } from "@/components/ui/data-table";
import type { DataTableColDef } from "@/components/ui/data-table/data-table-types";
import { addUserIcon as AddUserIcon } from "@/components/ui/icon";
import { MeetingSummaryListOfIssueDataGrid } from "@/features/ministry/meeting-summary/components/create-meeting-summary/table/meeting-summary-list-of-issue-data-grid";
import { RequiredSectionTitle } from "@/features/ministry/meeting-summary/components/view-meeting-summary/view-meeting-summary-shared";
import type { MeetingSummaryParticipants } from "@/features/ministry/meeting-summary/components/view-meeting-summary/view-meeting-summary-data";
import { useMeetingSummaryI18n } from "@/features/ministry/meeting-summary/use-meeting-summary-i18n";

export type ParticipantGroup = "pswg" | "ministry";

type ParticipantTableRow = {
  id: ParticipantGroup;
  group: "PSWG" | "Ministry";
  reporterName: string;
  reporterPosition: string;
  representativeName: string;
  representativePosition: string;
};

type EditableParticipantField = Exclude<
  keyof ParticipantTableRow,
  "id" | "group"
>;

const PARTICIPANT_FIELD_KEYS: Record<
  ParticipantGroup,
  Record<EditableParticipantField, keyof MeetingSummaryParticipants>
> = {
  pswg: {
    reporterName: "pswgReporter",
    reporterPosition: "pswgReporterPosition",
    representativeName: "pswgRepresentative",
    representativePosition: "pswgRepresentativePosition",
  },
  ministry: {
    reporterName: "ministryReporter",
    reporterPosition: "ministryReporterPosition",
    representativeName: "ministryRepresentative",
    representativePosition: "ministryRepresentativePosition",
  },
};

const PARTICIPANTS_TABLE_HEADER_HEIGHT = 50;
const PARTICIPANTS_TABLE_ROW_HEIGHT = 60;

type Props = {
  participants: MeetingSummaryParticipants;
  mode?: "display" | "edit";
  onChange?: (participants: MeetingSummaryParticipants) => void;
  onAddParticipants?: () => void;
  onUpdateParticipants?: (group: ParticipantGroup) => void;
  showTitle?: boolean;
  visibleGroups?: ParticipantGroup[];
};

function buildParticipantRows(
  participants: MeetingSummaryParticipants,
): ParticipantTableRow[] {
  return [
    {
      id: "pswg",
      group: "PSWG",
      reporterName: participants.pswgReporter,
      reporterPosition: participants.pswgReporterPosition,
      representativeName: participants.pswgRepresentative,
      representativePosition: participants.pswgRepresentativePosition,
    },
    {
      id: "ministry",
      group: "Ministry",
      reporterName: participants.ministryReporter,
      reporterPosition: participants.ministryReporterPosition,
      representativeName: participants.ministryRepresentative,
      representativePosition: participants.ministryRepresentativePosition,
    },
  ];
}

export function MeetingSummaryParticipantsTable({
  participants,
  mode = "display",
  onChange,
  onAddParticipants,
  onUpdateParticipants,
  showTitle = true,
  visibleGroups,
}: Props) {
  const theme = useTheme();
  const { text } = useMeetingSummaryI18n();
  const isDark = theme.palette.mode === "dark";
  const isEditable = mode === "edit";
  const rows = buildParticipantRows(participants).filter((row) =>
    visibleGroups ? visibleGroups.includes(row.id) : true,
  );

  function updateValue(
    group: ParticipantGroup,
    field: EditableParticipantField,
    value: string,
  ) {
    const participantKey = PARTICIPANT_FIELD_KEYS[group][field];
    onChange?.({ ...participants, [participantKey]: value });
  }

  function renderParticipantValue(
    row: ParticipantTableRow,
    field: EditableParticipantField,
  ) {
    if (!isEditable) {
      return row[field] || "-";
    }

    const label = `${row.group} ${field}`;

    return (
      <TextField
        fullWidth
        size="small"
        value={row[field]}
        onChange={(event) => updateValue(row.id, field, event.target.value)}
        placeholder={
          field.endsWith("Name")
            ? text.participants.enterName
            : text.participants.enterPosition
        }
        slotProps={{ htmlInput: { maxLength: 255, "aria-label": label } }}
      />
    );
  }

  const columns: DataTableColDef<ParticipantTableRow>[] = [
    {
      field: "id",
      headerName: text.columns.no,
      width: 52,
      minWidth: 52,
      align: "center",
      headerAlign: "center",
      sortable: false,
      filterable: false,
      disableColumnMenu: true,
      renderCell: (params) => (
        <DataTableNumberCell
          value={
            params.api.getRowIndexRelativeToVisibleRows(params.row.id) + 1
          }
        />
      ),
    },
    {
      field: "group",
      headerName: text.participants.group,
      width: 160,
      minWidth: 160,
      sortable: false,
      renderCell: (params) =>
        params.row.id === "pswg"
          ? text.participants.pswg
          : text.participants.ministry,
    },
    {
      field: "reporterName",
      headerName: text.participants.reporterName,
      width: 260,
      minWidth: 260,
      sortable: false,
      renderCell: (params) =>
        renderParticipantValue(params.row, "reporterName"),
    },
    {
      field: "reporterPosition",
      headerName: text.participants.reporterPosition,
      width: 260,
      minWidth: 260,
      sortable: false,
      renderCell: (params) =>
        renderParticipantValue(params.row, "reporterPosition"),
    },
    {
      field: "representativeName",
      headerName: text.participants.representativeName,
      width: 260,
      minWidth: 260,
      sortable: false,
      renderCell: (params) =>
        renderParticipantValue(params.row, "representativeName"),
    },
    {
      field: "representativePosition",
      headerName: text.participants.representativePosition,
      width: 260,
      minWidth: 260,
      sortable: false,
      renderCell: (params) =>
        renderParticipantValue(params.row, "representativePosition"),
    },
  ];

  if (!isEditable && onUpdateParticipants) {
    columns.push({
      field: "action",
      headerName: text.columns.action,
      width: 150,
      minWidth: 150,
      sortable: false,
      filterable: false,
      disableColumnMenu: true,
      renderCell: (params) => (
        <Button
          startIcon={
            <AutorenewOutlinedIcon sx={{ fontSize: 24, color: "#717680" }} />
          }
          onClick={() => onUpdateParticipants(params.row.id)}
          sx={{
            color: "#717680",
            textTransform: "none",
            fontSize: 12,
            fontWeight: 400,
            px: 1,
            minWidth: 0,
            whiteSpace: "nowrap",
            "& .MuiButton-startIcon": { mr: 0.5 },
            "&:hover": { bgcolor: "transparent", color: "#1a64a8" },
          }}
        >
          {text.participants.update}
        </Button>
      ),
    });
  }

  const dataGridSx: SxProps<Theme> = {
    border: "none",
    "& .MuiDataGrid-columnHeaders": {
      backgroundColor: isDark ? alpha("#ffffff", 0.06) : "#ddedfb",
      borderBottom: `1px solid ${isDark ? "#263244" : "#f5f5f5"}`,
    },
    "& .MuiDataGrid-columnHeader": {
      px: 2,
      backgroundColor: isDark ? alpha("#ffffff", 0.06) : "#ddedfb",
    },
    "& .MuiDataGrid-columnHeaderTitleContainer": { overflow: "visible" },
    "& .MuiDataGrid-columnHeaderTitle": {
      fontSize: 12,
      fontWeight: 400,
      whiteSpace: "nowrap",
      overflow: "visible",
      textOverflow: "clip",
      color: isDark ? alpha("#ffffff", 0.72) : "#717680",
    },
    "& .MuiDataGrid-cell": {
      px: 2,
      py: 0,
      color: isDark ? "#ffffff" : "#181d27",
      borderColor: isDark ? "#263244" : "#f5f5f5",
      borderBottom: `1px solid ${isDark ? "#263244" : "#f5f5f5"}`,
      bgcolor: isDark ? "#101828" : "#ffffff",
      display: "flex",
      alignItems: "center",
    },
    "& .MuiDataGrid-row, & .MuiDataGrid-row:hover": {
      bgcolor: isDark ? "#101828" : "#ffffff",
    },
    "& .MuiDataGrid-withBorderColor": {
      borderColor: isDark ? "#263244" : "#f5f5f5",
    },
    "& .MuiDataGrid-main": { overflow: "hidden" },
    "& .MuiDataGrid-virtualScroller": {
      overflowX: "auto !important",
      overflowY: "auto !important",
    },
    "& .MuiDataGrid-cell:focus, & .MuiDataGrid-cell:focus-within, & .MuiDataGrid-columnHeader:focus, & .MuiDataGrid-columnHeader:focus-within": {
      outline: "none",
    },
  };

  return (
    <Box sx={{ mb: 4 }}>
      {showTitle ? (
        <Box
          sx={{
            mb: 2,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 2,
          }}
        >
          <RequiredSectionTitle>{text.participants.title}</RequiredSectionTitle>

          {onAddParticipants ? (
            <Button
              type="button"
              onClick={onAddParticipants}
              startIcon={<AddUserIcon sx={{ fontSize: 24 }} />}
              sx={{
                minHeight: 30,
                px: 1.5,
                gap: 1.5,
                color: isDark ? "#60A5FA" : "#1A64A8",
                textTransform: "none",
                fontSize: 13,
                fontWeight: 500,
                lineHeight: 1,
                "& .MuiButton-startIcon": { m: 0 },
              }}
            >
              {text.participants.add}
            </Button>
          ) : null}
        </Box>
      ) : null}

      <MeetingSummaryListOfIssueDataGrid
        rows={rows}
        columns={columns}
        getRowId={(row) => row.id}
        height={
          PARTICIPANTS_TABLE_HEADER_HEIGHT +
          PARTICIPANTS_TABLE_ROW_HEIGHT * rows.length
        }
        rowHeight={PARTICIPANTS_TABLE_ROW_HEIGHT}
        columnHeaderHeight={PARTICIPANTS_TABLE_HEADER_HEIGHT}
        dataGridSx={dataGridSx}
        paperSx={{
          width: "100%",
          minWidth: 0,
          border: isDark
            ? `1px solid ${alpha("#ffffff", 0.1)}`
            : "1px solid #e9eaeb",
          borderRadius: "12px",
          overflow: "auto",
          bgcolor: isDark ? "#101828" : "#ffffff",
        }}
      />
    </Box>
  );
}
