"use client";

import PoWorkbenchDetailsGrid from "@/components/PoWorkbench/detailsGrid/PoWorkbenchDetailsGrid";
import PoWorkbenchDetailsHeader from "@/components/PoWorkbench/details/PoWorkbenchDetailsHeader";
import {
  PO_WORKBENCH_GRID_TEMPLATE_COLUMNS,
  PO_WORKBENCH_GRID_TEMPLATE_ROWS,
} from "@/components/PoWorkbench/layout/poWorkbenchShellLayout";
import PoWorkbenchRegion from "@/components/PoWorkbench/layout/PoWorkbenchRegion";
import PoWorkbenchLeftPane from "@/components/PoWorkbench/search/PoWorkbenchLeftPane";
import PoWorkbenchSearchCriteriaBar from "@/components/PoWorkbench/search/PoWorkbenchSearchCriteriaBar";
import {
  createDefaultAdvancedFilters,
  type PoWorkbenchAdvancedFilters,
} from "@/components/PoWorkbench/types";
import { usePoWorkbenchListSearch } from "@/components/PoWorkbench/search/usePoWorkbenchListSearch";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import Box from "@mui/material/Box";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import { useMediaQuery, useTheme } from "@mui/material";
import type { Theme } from "@mui/material/styles";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";

const ROOT_SHELL_SX = {
  alignSelf: "stretch",
  flex: 1,
  height: "100%",
  minHeight: 0,
  overflow: "hidden",
  boxSizing: "border-box" as const,
  border: 1,
  borderColor: "divider",
  borderRadius: { xs: 2, md: 0 },
  borderTopRightRadius: { xs: 2, md: 16 },
};

const compactStackSx = {
  display: "flex",
  flexDirection: "column" as const,
  gap: "1px",
  width: "100%",
  height: "100%",
  minHeight: 0,
  boxSizing: "border-box" as const,
  bgcolor: (theme: Theme) => theme.palette.divider,
};

const gridInnerSx = {
  display: "grid",
  gridTemplateColumns: PO_WORKBENCH_GRID_TEMPLATE_COLUMNS,
  gridTemplateRows: PO_WORKBENCH_GRID_TEMPLATE_ROWS,
  gap: "1px",
  width: "100%",
  height: "100%",
  minHeight: 0,
  boxSizing: "border-box" as const,
  bgcolor: (theme: Theme) => theme.palette.divider,
};

const compactBackBarSx = {
  flexShrink: 0,
  display: "flex",
  alignItems: "center",
  gap: 0.5,
  px: 0.5,
  py: 0.25,
  bgcolor: "background.paper",
  borderBottom: 1,
  borderColor: "divider",
} as const;

/**
 * Root layout for PO Workbench: 2×2 CSS grid (md+) or compact list/detail stack.
 * List data from `/po/list` via `usePoWorkbenchListSearch`.
 */
export default function PoWorkbenchShell() {
  const theme = useTheme();
  const { t } = useTranslation("poWorkbench");
  const isCompact = useMediaQuery(theme.breakpoints.down("md"), {
    noSsr: true,
  });

  const [poNumberQuery, setPoNumberQuery] = useState("");
  const [isAdvancedSearchOpen, setIsAdvancedSearchOpen] = useState(false);
  const [advancedFilters, setAdvancedFilters] =
    useState<PoWorkbenchAdvancedFilters>(() => createDefaultAdvancedFilters());
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [compactView, setCompactView] = useState<"list" | "detail">("list");

  const {
    listRows,
    totalMatches,
    isLoading,
    isLoadingMore,
    loadError,
    hasMore,
    loadMore,
  } = usePoWorkbenchListSearch({
    poNumberQuery,
    advancedFilters,
  });

  const selectedRow = useMemo(
    () => listRows.find((r) => r.id === selectedId) ?? null,
    [listRows, selectedId],
  );

  useEffect(() => {
    setSelectedId((prev) => {
      if (listRows.length === 0) {
        return null;
      }
      if (prev && listRows.some((r) => r.id === prev)) {
        return prev;
      }
      return listRows[0].id;
    });
  }, [listRows]);

  useEffect(() => {
    if (!isCompact) {
      setCompactView("list");
    }
  }, [isCompact]);

  useEffect(() => {
    if (isCompact && listRows.length === 0) {
      setCompactView("list");
    }
  }, [isCompact, listRows.length]);

  const handleSelectPo = useCallback(
    (id: string) => {
      setSelectedId(id);
      if (isCompact) {
        setCompactView("detail");
      }
    },
    [isCompact],
  );

  const criteriaBar = (
    <PoWorkbenchSearchCriteriaBar
      poNumber={poNumberQuery}
      onPoNumberChange={setPoNumberQuery}
      isAdvancedSearchOpen={isAdvancedSearchOpen}
      onToggleAdvancedSearch={() => setIsAdvancedSearchOpen((open) => !open)}
    />
  );

  const resultsPane = (
    <PoWorkbenchLeftPane
      isAdvancedSearchOpen={isAdvancedSearchOpen}
      results={listRows}
      totalMatches={totalMatches}
      isLoading={isLoading}
      isLoadingMore={isLoadingMore}
      loadError={loadError}
      hasMore={hasMore}
      onLoadMore={loadMore}
      selectedId={selectedId}
      onSelect={handleSelectPo}
      appliedAdvancedFilters={advancedFilters}
      onApplyAdvancedFilters={(filters) => {
        setAdvancedFilters(filters);
        setIsAdvancedSearchOpen(false);
      }}
      onResetAdvancedFilters={() =>
        setAdvancedFilters(createDefaultAdvancedFilters())
      }
    />
  );

  const detailsHeader = (
    <PoWorkbenchDetailsHeader row={selectedRow} isLoading={isLoading} />
  );
  const detailsBody = <PoWorkbenchDetailsGrid />;

  return (
    <Box sx={ROOT_SHELL_SX}>
      {!isCompact ? (
        <Box sx={gridInnerSx}>
          <PoWorkbenchRegion region="searchCriteria">
            {criteriaBar}
          </PoWorkbenchRegion>
          <PoWorkbenchRegion region="detailsHeader">
            {detailsHeader}
          </PoWorkbenchRegion>
          <PoWorkbenchRegion region="searchResults">
            {resultsPane}
          </PoWorkbenchRegion>
          <PoWorkbenchRegion region="details">{detailsBody}</PoWorkbenchRegion>
        </Box>
      ) : compactView === "list" ? (
        <Box sx={compactStackSx}>
          <PoWorkbenchRegion region="searchCriteria" heightMode="compactHug">
            {criteriaBar}
          </PoWorkbenchRegion>
          <PoWorkbenchRegion region="searchResults" heightMode="compactGrow">
            {resultsPane}
          </PoWorkbenchRegion>
        </Box>
      ) : (
        <Box sx={compactStackSx}>
          <Box sx={compactBackBarSx}>
            <IconButton
              size="small"
              aria-label={t("compact.ariaBackToList")}
              onClick={() => setCompactView("list")}
              edge="start"
            >
              <ArrowBackIcon />
            </IconButton>
            <Typography variant="body2" color="text.secondary" component="span">
              {t("compact.backToList")}
            </Typography>
          </Box>
          <PoWorkbenchRegion region="detailsHeader" heightMode="compactHug">
            {detailsHeader}
          </PoWorkbenchRegion>
          <PoWorkbenchRegion region="details" heightMode="compactGrow">
            {detailsBody}
          </PoWorkbenchRegion>
        </Box>
      )}
    </Box>
  );
}
