"use client";

import { useState } from "react";

import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import { alpha, useTheme } from "@mui/material/styles";
import type { GridColDef } from "@mui/x-data-grid";

import {
  DataTableDateCell,
  DataTableNumberCell,
} from "@/components/ui/data-table";
import {
  AgencyCell,
  MeetingRequestCell,
  StatusBadge,
  TableText,
} from "@/features/pswg/meeting-request/components/table/meeting-requests-table-cells";
import {
  MEETING_REQUEST_COLUMN_WIDTH,
  withFixedColumnWidths,
} from "@/features/pswg/meeting-request/components/table/meeting-requests-table-config";
import {
  getMeetingRequestFont,
  i18n,
  type UiLang,
} from "@/features/pswg/meeting-request/meeting-request-i18n";
import type {
  MeetingRequestRow,
  MeetingRequestStatus,
} from "@/features/pswg/meeting-request/meeting-request-data";

type TableColumnOptions = {
  onView?: (row: MeetingRequestRow) => void;
  onEdit?: (row: MeetingRequestRow) => void;
  onSend?: (row: MeetingRequestRow) => Promise<void> | void;
};

type MeetingRequestRowWithApi = MeetingRequestRow & {
  governmentAgencyLogo?: string | null;
};

function MoreVerticalIcon() {
  return (
    <Box component="svg" width={18} height={18} viewBox="0 0 20 20" fill="none">
      <path
        d="M10 5.25C10.6904 5.25 11.25 4.69036 11.25 4C11.25 3.30964 10.6904 2.75 10 2.75C9.30964 2.75 8.75 3.30964 8.75 4C8.75 4.69036 9.30964 5.25 10 5.25Z"
        fill="currentColor"
      />
      <path
        d="M10 11.25C10.6904 11.25 11.25 10.6904 11.25 10C11.25 9.30964 10.6904 8.75 10 8.75C9.30964 8.75 8.75 9.30964 8.75 10C8.75 10.6904 9.30964 11.25 10 11.25Z"
        fill="currentColor"
      />
      <path
        d="M10 17.25C10.6904 17.25 11.25 16.6904 11.25 16C11.25 15.3096 10.6904 14.75 10 14.75C9.30964 14.75 8.75 15.3096 8.75 16C8.75 16.6904 9.30964 17.25 10 17.25Z"
        fill="currentColor"
      />
    </Box>
  );
}

function ViewIcon() {
  return (
    <Box component="svg" width={16} height={16} viewBox="0 0 20 20" fill="none">
      <path
        d="M2.5 10S5.227 4.167 10 4.167S17.5 10 17.5 10S14.773 15.833 10 15.833S2.5 10 2.5 10Z"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path
        d="M10 12.5C11.381 12.5 12.5 11.381 12.5 10C12.5 8.619 11.381 7.5 10 7.5C8.619 7.5 7.5 8.619 7.5 10C7.5 11.381 8.619 12.5 10 12.5Z"
        stroke="currentColor"
        strokeWidth="1.5"
      />
    </Box>
  );
}

function EditIcon() {
  return (
    <Box component="svg" width={16} height={16} viewBox="0 0 20 20" fill="none">
      <path
        d="M11.25 4.167L15.833 8.75M3.75 16.25H8.333L16.667 7.917C17.219 7.365 17.219 6.469 16.667 5.917L14.083 3.333C13.531 2.781 12.635 2.781 12.083 3.333L3.75 11.667V16.25Z"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </Box>
  );
}

function SendIcon() {
  return (
    <Box component="svg" width={16} height={16} viewBox="0 0 20 20" fill="none">
      <path
        d="M17.5 2.5L8.75 11.25M17.5 2.5L11.944 17.5L8.75 11.25M17.5 2.5L2.5 8.056L8.75 11.25"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </Box>
  );
}

function ActionMenuCell({
  row,
  onView,
  onEdit,
  onSend,
}: {
  row: MeetingRequestRow;
  onView?: (row: MeetingRequestRow) => void;
  onEdit?: (row: MeetingRequestRow) => void;
  onSend?: (row: MeetingRequestRow) => Promise<void> | void;
}) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);

  const open = Boolean(anchorEl);
  const status = row.meetingStatus;

  // Every PSWG user with read access can open a request, including drafts.
  const canView = true;
  // Only users from the request owner's working group can manage a draft.
  const canEdit = status === "Drafted" && row.canManage === true;
  const canSend = status === "Drafted" && row.canManage === true;
  const hasIssues = row.issuesCount > 0;

  return (
    <Box
      onClick={(event) => event.stopPropagation()}
      onMouseDown={(event) => event.stopPropagation()}
    >
      <ButtonBase
        aria-label="Open meeting request actions"
        onClick={(event) => {
          event.stopPropagation();
          setAnchorEl(event.currentTarget);
        }}
        sx={{
          width: 30,
          height: 30,
          borderRadius: "6px",
          color: isDark ? alpha("#ffffff", 0.6) : "#98a2b3",
          display: "grid",
          placeItems: "center",
          "&:hover": {
            bgcolor: isDark ? alpha("#ffffff", 0.08) : "#f5f5f5",
            color: isDark ? "#ffffff" : "#667085",
          },
        }}
      >
        <MoreVerticalIcon />
      </ButtonBase>

      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={() => setAnchorEl(null)}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        slotProps={{
          paper: {
            sx: {
              mt: 0.5,
              width: 172,
              borderRadius: "8px",
              border: `1px solid ${
                isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"
              }`,
              backgroundColor: isDark ? "#101828" : "#ffffff",
              boxShadow: "0px 12px 30px rgba(16, 24, 40, 0.16)",
              overflow: "hidden",
            },
          },
        }}
      >
        {canView && (
          <MenuItem
            onClick={(event) => {
              event.stopPropagation();
              setAnchorEl(null);
              onView?.(row);
            }}
            sx={{
              gap: 1.25,
              minHeight: 36,
              fontSize: 13,
              color: isDark ? alpha("#ffffff", 0.86) : "#344054",
            }}
          >
            <ViewIcon />
            View Detail
          </MenuItem>
        )}

        {canEdit && (
          <MenuItem
            onClick={(event) => {
              event.stopPropagation();
              setAnchorEl(null);
              onEdit?.(row);
            }}
            sx={{
              gap: 1.25,
              minHeight: 36,
              fontSize: 13,
              color: isDark ? alpha("#ffffff", 0.86) : "#344054",
            }}
          >
            <EditIcon />
            Edit
          </MenuItem>
        )}

        {canSend && (
          <MenuItem
            disabled={!hasIssues}
            onClick={(event) => {
              event.stopPropagation();
              setAnchorEl(null);
              void onSend?.(row);
            }}
            sx={{
              gap: 1.25,
              minHeight: 36,
              fontSize: 13,
              color: isDark ? alpha("#ffffff", 0.86) : "#344054",
            }}
          >
            <SendIcon />
            {hasIssues ? "Send Request" : "Add Issue Before Sending"}
          </MenuItem>
        )}
      </Menu>
    </Box>
  );
}

export function getMeetingRequestsTableColumns(
  language: UiLang,
  options: TableColumnOptions = {},
): GridColDef<MeetingRequestRow>[] {
  const t = i18n(language);

  return withFixedColumnWidths([
    {
      field: "id",
      headerName: t.no,
      width: 90,
      minWidth: 90,
      align: "center",
      headerAlign: "center",
      sortable: false,
      renderCell: (params) => (
        <DataTableNumberCell value={params.value as string | number | null} />
      ),
    },
    {
      field: "workingGroup",
      headerName: t.workingGroup,
      width: 240,
      minWidth: 220,
      sortable: false,
      renderCell: (params) => (
        <TableText
          value={String(params.value || "-")}
          fontFamily={getMeetingRequestFont(language)}
        />
      ),
    },
    {
      field: "title",
      headerName: t.meetingTitle,
      width: 220,
      minWidth: 220,
      headerAlign: "center",
      sortable: false,
      renderCell: (params) => (
        <TableText
          value={String(params.value || "-")}
          fontFamily={getMeetingRequestFont(language)}
        />
      ),
    },
    {
      field: "meetingDescription",
      headerName: t.meetingDescription,
      width: 300,
      sortable: false,
      renderCell: (params) => (
        <TableText
          value={String(params.value || "-")}
          fontFamily={getMeetingRequestFont(language)}
        />
      ),
    },
    {
      field: "issuesCount",
      headerName: t.issuesCount,
      width: 100,
      align: "center",
      headerAlign: "left",
      sortable: false,
      renderCell: (params) => (
        <DataTableNumberCell value={params.value as string | number | null} />
      ),
    },
    {
      field: "meetingStatus",
      headerName: t.meetingStatus,
      width: 145,
      align: "center",
      headerAlign: "center",
      sortable: false,
      renderCell: (params) => (
        <StatusBadge
          status={params.value as MeetingRequestStatus}
          language={language}
        />
      ),
    },
    {
      field: "meetingDate",
      headerName: t.meetingDate,
      width: 161,
      align: "center",
      headerAlign: "center",
      sortable: false,
      renderCell: (params) => (
        <DataTableDateCell value={params.value} showTooltip={false} />
      ),
    },
    {
      field: "governmentAgency",
      headerName: t.governmentAgency,
      width: 150,
      headerAlign: "center",
      sortable: false,
      renderCell: (params) => {
        const row = params.row as MeetingRequestRowWithApi;

        return (
          <AgencyCell
            agency={String(row.governmentAgency || "-")}
            logo={row.governmentAgencyLogo}
          />
        );
      },
    },
    {
      field: "meetingRequest",
      headerName: t.meetingRequest,
      width: MEETING_REQUEST_COLUMN_WIDTH,
      align: "center",
      headerAlign: "center",
      sortable: false,
      renderCell: (params) => (
        <MeetingRequestCell label={String(params.value || "-")} wrap />
      ),
    },
    {
      field: "action",
      headerName: t.action,
      width: 70,
      align: "center",
      headerAlign: "center",
      sortable: false,
      filterable: false,
      renderCell: (params) => (
        <ActionMenuCell
          row={params.row}
          onView={options.onView}
          onEdit={options.onEdit}
          onSend={options.onSend}
        />
      ),
    },
  ]);
}
