"use client";

import type {
  MouseEvent,
} from "react";

import {
  Box,
  Button,
  Chip,
  TableCell,
  TableRow,
  useTheme,
} from "@mui/material";

import {
  getTranslationModuleLabel,
} from "../constants/translation-modules";

import type {
  TranslationPageGroup,
} from "../hook/use-translation-page-groups";

import {
  formatTranslationDateTime,
} from "./translation-management-utils";

function ChevronIcon({
  open,
}: {
  open: boolean;
}) {
  return (
    <Box
      component="span"
      sx={{
        width: 9,
        height: 9,
        display: "inline-block",
        flexShrink: 0,
        borderRight:
          "2px solid currentColor",
        borderBottom:
          "2px solid currentColor",
        transform: open
          ? "rotate(225deg)"
          : "rotate(45deg)",
        transition:
          "transform 160ms ease",
        mt: open
          ? 0.45
          : -0.35,
      }}
    />
  );
}

type SubPageItem = {
  group: TranslationPageGroup;
  depth: number;
};

type Props = {
  group: TranslationPageGroup;
  rowNumber: number;
  subPages?: SubPageItem[];
  open?: boolean;
  onOpenChange?: (
    open: boolean,
  ) => void;
  locale: "en" | "km";
  activeLabel: string;
  inactiveLabel: string;
  onSelectSubPage: (
    group: TranslationPageGroup,
  ) => void;
  onOpenPageMenu: (
    event: MouseEvent<HTMLElement>,
    group: TranslationPageGroup,
  ) => void;
};

export default function TranslationManagementTableRow({
  group,
  rowNumber,
  subPages = [],
  open = false,
  onOpenChange,
  locale,
  activeLabel,
  inactiveLabel,
  onSelectSubPage,
  onOpenPageMenu,
}: Props) {
  const theme = useTheme();

  const hasSubPages =
    subPages.length > 0;

  const renderStatus = (
    item: TranslationPageGroup,
  ) => (
    <Chip
      size="small"
      label={
        item.isActive
          ? activeLabel
          : inactiveLabel
      }
      color={
        item.isActive
          ? "success"
          : "default"
      }
      variant="outlined"
    />
  );

  return (
    <>
      {/* ROOT PAGE */}
      <TableRow hover>
        <TableCell>
          {rowNumber}
        </TableCell>

        <TableCell>
          <Chip
            size="small"
            label={getTranslationModuleLabel(
              group.module,
            )}
            color="primary"
            variant="outlined"
          />
        </TableCell>

        <TableCell>
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 0.75,
            }}
          >
            <Chip
              size="small"
              label={group.page}
              variant="outlined"
            />

            {/* Show dropdown icon only when there are Sub Pages */}
            {hasSubPages ? (
              <Button
                type="button"
                aria-label={
                  open
                    ? "Collapse sub pages"
                    : "Expand sub pages"
                }
                aria-expanded={open}
                onClick={(event) => {
                  event.stopPropagation();

                  onOpenChange?.(
                    !open,
                  );
                }}
                sx={{
                  minWidth: 30,
                  width: 30,
                  height: 30,
                  p: 0,
                  borderRadius: "50%",
                  color:
                    "text.secondary",
                  flexShrink: 0,
                }}
              >
                <ChevronIcon
                  open={open}
                />
              </Button>
            ) : null}
          </Box>
        </TableCell>

        <TableCell>
          <Box
            sx={{
              minWidth: 220,
              maxWidth: 320,
              overflow: "hidden",
              textOverflow:
                "ellipsis",
              whiteSpace: "nowrap",
            }}
            title={group.englishText}
          >
            {group.englishText}
          </Box>
        </TableCell>

        <TableCell>
          <Box
            sx={{
              minWidth: 240,
              maxWidth: 360,
              overflow: "hidden",
              textOverflow:
                "ellipsis",
              whiteSpace: "nowrap",
            }}
            title={group.khmerText}
          >
            {group.khmerText}
          </Box>
        </TableCell>

        <TableCell>
          {renderStatus(group)}
        </TableCell>

        <TableCell
          sx={{
            whiteSpace: "nowrap",
            color:
              "text.secondary",
          }}
        >
          {formatTranslationDateTime(
            group.createdAt,
            locale,
          )}
        </TableCell>

        <TableCell
          sx={{
            whiteSpace: "nowrap",
            color:
              "text.secondary",
          }}
        >
          {formatTranslationDateTime(
            group.updatedAt,
            locale,
          )}
        </TableCell>

        <TableCell align="right">
          <Button
            type="button"
            onClick={(event) =>
              onOpenPageMenu(
                event,
                group,
              )
            }
            sx={{
              minWidth: 36,
              width: 36,
              height: 36,
              p: 0,
              borderRadius:
                "50%",
              color:
                "text.secondary",
              fontSize: 24,
              lineHeight: 1,
            }}
          >
            ⋮
          </Button>
        </TableCell>
      </TableRow>

      {/* INLINE DROPDOWN TABLE ROWS */}
      {open
        ? subPages.map(
            (
              {
                group:
                  subPage,
                depth,
              },
              index,
            ) => (
              <TableRow
                key={`sub-page-${subPage.id}`}
                hover
                onClick={() =>
                  onSelectSubPage(
                    subPage,
                  )
                }
                sx={{
                  cursor:
                    "pointer",
                  bgcolor:
                    theme.palette.mode ===
                    "dark"
                      ? "rgba(148,163,184,.035)"
                      : "rgba(15,82,140,.025)",
                }}
              >
                <TableCell
                  sx={{
                    color:
                      "text.secondary",
                  }}
                >
                  {rowNumber + index + 1}
                </TableCell>

                <TableCell>
                  <Chip
                    size="small"
                    label={getTranslationModuleLabel(
                      subPage.module,
                    )}
                    color="primary"
                    variant="outlined"
                  />
                </TableCell>

                <TableCell>
                  <Box
                    sx={{
                      display:
                        "flex",
                      alignItems:
                        "center",
                      gap: 0.75,
                      pl:
                        Math.max(
                          1,
                          depth,
                        ) *
                        2.5,
                    }}
                  >
                    <Box
                      sx={{
                        width: 6,
                        height: 6,
                        borderRadius:
                          "50%",
                        bgcolor:
                          "text.disabled",
                        flexShrink: 0,
                      }}
                    />

                    <Chip
                      size="small"
                      label={
                        subPage.page
                      }
                      variant="outlined"
                    />
                  </Box>
                </TableCell>

                <TableCell>
                  <Box
                    sx={{
                      minWidth:
                        220,
                      maxWidth:
                        320,
                      overflow:
                        "hidden",
                      textOverflow:
                        "ellipsis",
                      whiteSpace:
                        "nowrap",
                    }}
                    title={
                      subPage.englishText
                    }
                  >
                    {
                      subPage.englishText
                    }
                  </Box>
                </TableCell>

                <TableCell>
                  <Box
                    sx={{
                      minWidth:
                        240,
                      maxWidth:
                        360,
                      overflow:
                        "hidden",
                      textOverflow:
                        "ellipsis",
                      whiteSpace:
                        "nowrap",
                    }}
                    title={
                      subPage.khmerText
                    }
                  >
                    {
                      subPage.khmerText
                    }
                  </Box>
                </TableCell>

                <TableCell>
                  {renderStatus(
                    subPage,
                  )}
                </TableCell>

                <TableCell
                  sx={{
                    whiteSpace:
                      "nowrap",
                    color:
                      "text.secondary",
                  }}
                >
                  {formatTranslationDateTime(
                    subPage.createdAt,
                    locale,
                  )}
                </TableCell>

                <TableCell
                  sx={{
                    whiteSpace:
                      "nowrap",
                    color:
                      "text.secondary",
                  }}
                >
                  {formatTranslationDateTime(
                    subPage.updatedAt,
                    locale,
                  )}
                </TableCell>

                <TableCell align="right">
                  <Button
                    type="button"
                    onClick={(
                      event,
                    ) => {
                      event.stopPropagation();

                      onOpenPageMenu(
                        event,
                        subPage,
                      );
                    }}
                    sx={{
                      minWidth:
                        36,
                      width: 36,
                      height: 36,
                      p: 0,
                      borderRadius:
                        "50%",
                      color:
                        "text.secondary",
                      fontSize: 24,
                      lineHeight: 1,
                    }}
                  >
                    ⋮
                  </Button>
                </TableCell>
              </TableRow>
            ),
          )
        : null}
    </>
  );
}