"use client";

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

import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  InputAdornment,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  useTheme,
} from "@mui/material";

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

import type {
  Translation,
} from "../types/translation-types";
import { formatTranslationPageNumber, getTranslationPaginationItems } from "./translation-pagination";
import { searchTranslationLabels } from "./translation-label-search";

type UiLocale =
  | "en"
  | "km";

type ViewDetailText = {
  back: string;
  title: string;
  subtitle: string;
  module: string;
  page: string;
  addNewLabel: string;
  searchPlaceholder: string;
  no: string;
  translationKey: string;
  englishText: string;
  khmerText: string;
  status: string;
  active: string;
  inactive: string;
  createdAt: string;
  updatedAt: string;
  actions: string;
  noLabels: string;
};

type Props = {
  locale: UiLocale;
  appFontFamily: string;
  group: TranslationPageGroup;
  labels: Translation[];
  loading: boolean;
  error: string;
  search: string;
  text: ViewDetailText;
  onSearchChange: (
    value: string,
  ) => void;
  onBack: () => void;
  onAddNewLabel: (
    group:
      TranslationPageGroup,
  ) => void;
  onOpenActionMenu: (
    event:
      MouseEvent<HTMLElement>,
    item: Translation,
  ) => void;
};

function formatDateTime(
  value:
    | string
    | null
    | undefined,
  locale: UiLocale,
): string {
  if (!value) {
    return "-";
  }

  const date =
    new Date(value);

  if (
    Number.isNaN(
      date.getTime(),
    )
  ) {
    return value;
  }

  return new Intl.DateTimeFormat(
    locale === "km"
      ? "km-KH"
      : "en-GB",
    {
      year: "numeric",
      month: "short",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    },
  ).format(date);
}

export default function TranslationManagementViewDetail({
  locale,
  appFontFamily,
  group,
  labels,
  loading,
  error,
  search,
  text,
  onSearchChange,
  onBack,
  onAddNewLabel,
  onOpenActionMenu,
}: Props) {
  const theme =
    useTheme();

  const PAGE_SIZE = 10;

  const [
    currentPage,
    setCurrentPage,
  ] = useState(1);

  const filteredLabels = searchTranslationLabels(labels, search);

  const totalPages =
    Math.max(
      1,
      Math.ceil(
        filteredLabels.length /
          PAGE_SIZE,
      ),
    );

  const safePage =
    Math.min(
      currentPage,
      totalPages,
    );

  const paginatedLabels =
    filteredLabels.slice(
      (safePage - 1) *
        PAGE_SIZE,
      safePage *
        PAGE_SIZE,
    );

  const handleSearchChange = (
    event:
      ChangeEvent<HTMLInputElement>,
  ) => {
    setCurrentPage(1);

    onSearchChange(
      event.target.value,
    );
  };

  return (
    <Box
      sx={{
        width: "100%",
        fontFamily:
          appFontFamily,

        "& .MuiButton-root": {
          fontFamily:
            appFontFamily,
        },

        "& .MuiTableCell-root":
          {
            fontFamily:
              appFontFamily,
          },

        "& .MuiInputBase-root":
          {
            fontFamily:
              appFontFamily,
          },
      }}
    >
      {/* HEADER */}
      <Box
        sx={{
          display: "flex",
          flexWrap: "wrap",
          alignItems: {
            xs: "stretch",
            md: "center",
          },
          justifyContent:
            "space-between",
          gap: {
            xs: 1.5,
            md: 2,
          },
          mb: 2,
        }}
      >
        <Box
          sx={{
            display: "flex",
            flexDirection: {
              xs: "column",
              sm: "row",
            },
            alignItems:
              "flex-start",
            gap: {
              xs: 1.25,
              sm: 2,
            },
            minWidth: 0,
            flex: "1 1 auto",
          }}
        >
          <Button
            type="button"
            variant="text"
            onClick={onBack}
            sx={{
              minWidth: "auto",
              height: 40,
              px: 0,
              mt: 0,
              flexShrink: 0,
              color:
                "text.secondary",
              textTransform:
                "none",
              fontWeight: 600,
              fontSize: 15,
            }}
          >
            <Box
              component="span"
              sx={{
                mr: 0.75,
                fontSize: 22,
                lineHeight: 1,
              }}
            >
              ←
            </Box>

            {text.back}
          </Button>

          <Box
            sx={{
              display: { xs: "none", sm: "block" },
              width: "1px",
              minWidth: "1px",
              height: {
                xs: 58,
                sm: 64,
              },
              bgcolor:
                "divider",
              flexShrink: 0,
            }}
          />

          <Box
            sx={{
              minWidth: 0,
            }}
          >
            <Box
              component="h1"
              sx={{
                m: 0,
                fontWeight: 800,
                fontSize: {
                  xs: 26,
                  md: 32,
                },
                lineHeight:
                  locale === "km"
                    ? 1.55
                    : 1.2,
                wordBreak:
                  "break-word",
              }}
            >
              {text.title}
            </Box>

            <Box
              component="p"
              sx={{
                mt: 0.75,
                mb: 0,
                color:
                  "text.secondary",
                fontSize: 14,
                lineHeight:
                  locale === "km"
                    ? 1.8
                    : 1.5,
              }}
            >
              {text.subtitle}
            </Box>
          </Box>
        </Box>

        <Button
          variant="contained"
          onClick={() =>
            onAddNewLabel(
              group,
            )
          }
          sx={{
            minHeight: 46,
            px: 2.5,
            borderRadius: 2,
            textTransform:
              "none",
            fontWeight: 700,
            alignSelf: {
              xs: "flex-start",
              md: "flex-start",
            },
            flexShrink: 0,
          }}
        >
          <Box
            component="span"
            sx={{
              mr: 0.75,
              fontSize: 21,
              lineHeight: 1,
            }}
          >
            +
          </Box>

          {text.addNewLabel}
        </Button>

        {/* SEARCH */}
        <Box sx={{ width: "100%", mt: { xs: 0, md: 0.25 } }}>
        <TextField
          size="small"
          value={search}
          placeholder={
            text.searchPlaceholder
          }
          onChange={
            handleSearchChange
          }
          slotProps={{
            input: {
              startAdornment:
                (
                  <InputAdornment position="start">
                    <Box
                      component="span"
                      sx={{
                        color:
                          "text.secondary",
                      }}
                    >
                      ⌕
                    </Box>
                  </InputAdornment>
                ),
            },
          }}
          sx={{
            width: {
              xs: "100%",
              sm: 320,
              md: 360,
            },
            "& .MuiOutlinedInput-root": {
              borderRadius: "12px",
            },
          }}
        />
        </Box>
      </Box>

      {/* TABLE */}
      <Paper
        variant="outlined"
        sx={{
          overflow: "hidden",
          borderRadius: 3,
        }}
      >
        {error ? (
          <Alert
            severity="error"
            sx={{ m: 2 }}
          >
            {error}
          </Alert>
        ) : null}

        <TableContainer
          sx={{
            width: "100%",
            overflowX: "auto",

            // Keep horizontal scrolling available,
            // but hide the visible scrollbar.
            scrollbarWidth: "none",
            msOverflowStyle: "none",

            "&::-webkit-scrollbar": {
              display: "none",
            },
          }}
        >
          <Table
            sx={{
              minWidth: 1360,

              "& th": {
                whiteSpace:
                  "nowrap",
                fontWeight: 700,
              },
            }}
          >
            <TableHead>
              <TableRow
                sx={{
                  bgcolor:
                    theme.palette.mode ===
                    "dark"
                      ? "rgba(148,163,184,.08)"
                      : "#eaf2fc",
                }}
              >
                <TableCell
                  sx={{
                    width: 72,
                    minWidth: 72,
                  }}
                >
                  {text.no}
                </TableCell>

                <TableCell
                  sx={{
                    minWidth: 210,
                  }}
                >
                  {
                    text.translationKey
                  }
                </TableCell>

                <TableCell
                  sx={{
                    minWidth: 220,
                  }}
                >
                  {
                    text.englishText
                  }
                </TableCell>

                <TableCell
                  sx={{
                    minWidth: 240,
                  }}
                >
                  {
                    text.khmerText
                  }
                </TableCell>

                <TableCell
                  sx={{
                    minWidth: 110,
                  }}
                >
                  {text.status}
                </TableCell>

                <TableCell
                  sx={{
                    minWidth: 170,
                  }}
                >
                  {
                    text.createdAt
                  }
                </TableCell>

                <TableCell
                  sx={{
                    minWidth: 170,
                  }}
                >
                  {
                    text.updatedAt
                  }
                </TableCell>

                <TableCell
                  align="center"
                  sx={{
                    width: 90,
                    minWidth: 90,
                  }}
                >
                  {text.actions}
                </TableCell>
              </TableRow>
            </TableHead>

            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell
                    colSpan={8}
                    align="center"
                    sx={{ py: 8 }}
                  >
                    <CircularProgress
                      size={26}
                    />
                  </TableCell>
                </TableRow>
              ) : filteredLabels.length ===
                0 ? (
                <TableRow>
                  <TableCell
                    colSpan={8}
                    align="center"
                    sx={{
                      py: 8,
                      color:
                        "text.secondary",
                    }}
                  >
                    {text.noLabels}
                  </TableCell>
                </TableRow>
              ) : (
                paginatedLabels.map(
                  (
                    item,
                    index,
                  ) => (
                    <TableRow
                      key={item.id}
                      hover
                    >
                      <TableCell>
                        {(safePage - 1) *
                          PAGE_SIZE +
                          index +
                          1}
                      </TableCell>

                      <TableCell>
                        <Chip
                          size="small"
                          label={
                            item.translationKey
                          }
                          variant="outlined"
                          sx={{
                            maxWidth: 280,
                            fontFamily:
                              "monospace",
                            color:
                              theme.palette.mode ===
                              "dark"
                                ? "#c084fc"
                                : "#7c3aed",
                          }}
                        />
                      </TableCell>

                      <TableCell>
                        <Box
                          sx={{
                            maxWidth: 300,
                            overflow:
                              "hidden",
                            textOverflow:
                              "ellipsis",
                            whiteSpace:
                              "nowrap",
                          }}
                          title={
                            item.englishText
                          }
                        >
                          {
                            item.englishText
                          }
                        </Box>
                      </TableCell>

                      <TableCell>
                        <Box
                          sx={{
                            maxWidth: 340,
                            overflow:
                              "hidden",
                            textOverflow:
                              "ellipsis",
                            whiteSpace:
                              "nowrap",
                          }}
                          title={
                            item.khmerText
                          }
                        >
                          {
                            item.khmerText
                          }
                        </Box>
                      </TableCell>

                      <TableCell>
                        <Chip
                          size="small"
                          label={
                            item.isActive
                              ? text.active
                              : text.inactive
                          }
                          color={
                            item.isActive
                              ? "success"
                              : "default"
                          }
                          variant="outlined"
                        />
                      </TableCell>

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

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

                      <TableCell
                        align="center"
                      >
                        <Button
                          type="button"
                          aria-label={text.actions}
                          aria-haspopup="menu"
                          onClick={(
                            event,
                          ) =>
                            onOpenActionMenu(
                              event,
                              item,
                            )
                          }
                          sx={{
                            minWidth: 36,
                            width: 36,
                            height: 36,
                            p: 0,
                            borderRadius:
                              "50%",
                            color:
                              "text.secondary",
                            fontSize: 24,
                          }}
                        >
                          ⋮
                        </Button>
                      </TableCell>
                    </TableRow>
                  ),
                )
              )}
            </TableBody>
          </Table>
        </TableContainer>

        {/* PAGINATION FOOTER */}
        <Box
          sx={{
            px: 2,
            py: 1.5,
            borderTop:
              "1px solid",
            borderColor:
              "divider",
            display: "grid",
            gridTemplateColumns: {
              xs: "1fr",
              sm: "1fr auto 1fr",
            },
            alignItems: "center",
            gap: 1.5,
          }}
        >
          {/* PREVIOUS */}
          <Box
            sx={{
              justifySelf: {
                xs: "center",
                sm: "start",
              },
              order: {
                xs: 2,
                sm: 1,
              },
            }}
          >
            <Button
              size="small"
              variant="outlined"
              disabled={
                safePage <= 1
              }
              onClick={() =>
                setCurrentPage(
                  Math.max(
                    1,
                    safePage - 1,
                  ),
                )
              }
              sx={{
                minWidth: 108,
                height: 34,
                px: 1.5,
                borderRadius: 1.5,
                textTransform:
                  "none",
                fontWeight: 500,
                color:
                  "text.secondary",
                borderColor:
                  "divider",
              }}
            >
              <Box
                component="span"
                sx={{
                  mr: 0.75,
                  mt: "-1px",
                  fontSize: 18,
                  lineHeight: 1,
                }}
              >
                ‹
              </Box>

              {locale === "km"
                ? "មុន"
                : "Previous"}
            </Button>
          </Box>

          {/* PAGE NUMBERS */}
          <Box
            sx={{
              display: "flex",
              alignItems:
                "center",
              justifyContent:
                "center",
              gap: 0.45,
              flexWrap: "wrap",
              order: {
                xs: 1,
                sm: 2,
              },
            }}
          >
            {getTranslationPaginationItems(safePage, totalPages).map((pageNumber, index) =>
              pageNumber === "ellipsis" ? (
                <Box component="span" aria-hidden="true" key={`gap-${index}`} sx={{ px: 0.5, color: "text.secondary" }}>…</Box>
              ) : (
                <Button
                  key={pageNumber}
                  type="button"
                  size="small"
                  aria-label={`${text.page} ${formatTranslationPageNumber(pageNumber, locale)}`}
                  aria-current={pageNumber === safePage ? "page" : undefined}
                  onClick={() => setCurrentPage(pageNumber)}
                  sx={{
                    minWidth: 30,
                    width: 30,
                    height: 30,
                    p: 0,
                    borderRadius: 1.5,
                    textTransform: "none",
                    fontSize: 14,
                    fontWeight: pageNumber === safePage ? 700 : 500,
                    color: pageNumber === safePage ? "primary.main" : "text.secondary",
                    bgcolor: pageNumber === safePage
                      ? theme.palette.mode === "dark"
                        ? "rgba(59,130,246,.22)"
                        : "#EAF3FF"
                      : "transparent",
                  }}
                >
                  {formatTranslationPageNumber(pageNumber, locale)}
                </Button>
              ),
            )}
          </Box>

          {/* NEXT */}
          <Box
            sx={{
              justifySelf: {
                xs: "center",
                sm: "end",
              },
              order: 3,
            }}
          >
            <Button
              size="small"
              variant="outlined"
              disabled={
                safePage >=
                totalPages
              }
              onClick={() =>
                setCurrentPage(
                  Math.min(
                    totalPages,
                    safePage + 1,
                  ),
                )
              }
              sx={{
                minWidth: 82,
                height: 34,
                px: 1.5,
                borderRadius: 1.5,
                textTransform:
                  "none",
                fontWeight: 500,
                color:
                  "text.secondary",
                borderColor:
                  "divider",
              }}
            >
              {locale === "km"
                ? "បន្ទាប់"
                : "Next"}

              <Box
                component="span"
                sx={{
                  ml: 0.75,
                  mt: "-1px",
                  fontSize: 18,
                  lineHeight: 1,
                }}
              >
                ›
              </Box>
            </Button>
          </Box>
        </Box>
      </Paper>
    </Box>
  );
}
