"use client";

import Box from "@mui/material/Box";
import { useEffect, useMemo, useState } from "react";
import {
  MOCK_WORKBENCH_SEARCH_RESULTS,
  WORKBENCH_GRID_TEMPLATE_COLUMNS,
  WORKBENCH_GRID_TEMPLATE_ROWS,
} from "@/components/PoWorkbench/mock/workbenchMockData";
import PoWorkbenchDetailsPlaceholder from "@/components/PoWorkbench/PoWorkbenchDetailsPlaceholder";
import PoWorkbenchRegion from "@/components/PoWorkbench/PoWorkbenchRegion";
import PoWorkbenchSearchCriteriaBar from "@/components/PoWorkbench/PoWorkbenchSearchCriteriaBar";
import PoWorkbenchLeftPane from "@/components/PoWorkbench/PoWorkbenchSearchResultsPane";
import {
  DEFAULT_ADVANCED_FILTERS,
  type PoWorkbenchAdvancedFilters,
} from "@/components/PoWorkbench/types";

/**
 * Root layout for PO Workbench: a 2×2 CSS Grid with configurable column and row templates
 * defined in {@link WORKBENCH_GRID_TEMPLATE_COLUMNS} and {@link WORKBENCH_GRID_TEMPLATE_ROWS}.
 * Search UI uses mock data until `/po/list` is integrated.
 */
export default function PoWorkbenchShell() {
  const [poNumberQuery, setPoNumberQuery] = useState("");
  const [isAdvancedSearchOpen, setIsAdvancedSearchOpen] = useState(false);
  const [advancedFilters, setAdvancedFilters] = useState<PoWorkbenchAdvancedFilters>(
    { ...DEFAULT_ADVANCED_FILTERS },
  );
  const [selectedId, setSelectedId] = useState<string | null>(
    () => MOCK_WORKBENCH_SEARCH_RESULTS[0]?.id ?? null,
  );

  const filteredResults = useMemo(() => {
    let rows = MOCK_WORKBENCH_SEARCH_RESULTS;

    const q = poNumberQuery.trim().toLowerCase();
    if (q) {
      rows = rows.filter((row) => row.poNumber.toLowerCase().includes(q));
    }

    const supplierQ = advancedFilters.supplierQuery.trim().toLowerCase();
    if (supplierQ) {
      rows = rows.filter((row) =>
        row.supplierName.toLowerCase().includes(supplierQ),
      );
    }

    if (advancedFilters.orderDateFrom) {
      rows = rows.filter((row) => row.orderDate >= advancedFilters.orderDateFrom);
    }
    if (advancedFilters.orderDateTo) {
      rows = rows.filter((row) => row.orderDate <= advancedFilters.orderDateTo);
    }

    if (advancedFilters.etaDateFrom) {
      rows = rows.filter(
        (row) => row.estimatedArrivalDate >= advancedFilters.etaDateFrom,
      );
    }
    if (advancedFilters.etaDateTo) {
      rows = rows.filter(
        (row) => row.estimatedArrivalDate <= advancedFilters.etaDateTo,
      );
    }

    if (advancedFilters.reportStatus !== "ALL") {
      const want = advancedFilters.reportStatus === "REPORTED";
      rows = rows.filter((row) => row.reported === want);
    }

    if (advancedFilters.receiveStatus !== "ALL") {
      const want = advancedFilters.receiveStatus === "RECEIVED";
      rows = rows.filter((row) => row.received === want);
    }

    return rows;
  }, [poNumberQuery, advancedFilters]);

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

  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: WORKBENCH_GRID_TEMPLATE_COLUMNS,
        gridTemplateRows: WORKBENCH_GRID_TEMPLATE_ROWS,
        gap: 0,
        width: "100%",
        height: "100%",
        minHeight: 0,
      }}
    >
      <PoWorkbenchRegion region="searchCriteria">
        <PoWorkbenchSearchCriteriaBar
          poNumber={poNumberQuery}
          onPoNumberChange={setPoNumberQuery}
          isAdvancedSearchOpen={isAdvancedSearchOpen}
          onToggleAdvancedSearch={() => setIsAdvancedSearchOpen((open) => !open)}
        />
      </PoWorkbenchRegion>
      <PoWorkbenchRegion region="detailsHeader">
        <PoWorkbenchDetailsPlaceholder region="detailsHeader" />
      </PoWorkbenchRegion>
      <PoWorkbenchRegion region="searchResults">
        <PoWorkbenchLeftPane
          isAdvancedSearchOpen={isAdvancedSearchOpen}
          results={filteredResults}
          selectedId={selectedId}
          onSelect={setSelectedId}
          appliedAdvancedFilters={advancedFilters}
          onApplyAdvancedFilters={setAdvancedFilters}
          onResetAdvancedFilters={() => setAdvancedFilters({ ...DEFAULT_ADVANCED_FILTERS })}
        />
      </PoWorkbenchRegion>
      <PoWorkbenchRegion region="details">
        <PoWorkbenchDetailsPlaceholder region="details" />
      </PoWorkbenchRegion>
    </Box>
  );
}
