"use client";

import {
  type PoWorkbenchAdvancedFilters,
  type PoWorkbenchListRow,
  createDefaultAdvancedFilters,
} from "@/components/PoWorkbench/types";
import Box from "@mui/material/Box";
import Slide from "@mui/material/Slide";
import { useTheme } from "@mui/material/styles";
import { useEffect, useState } from "react";
import PoWorkbenchAdvancedSearchPanel from "@/components/PoWorkbench/search/PoWorkbenchAdvancedSearchPanel";
import PoWorkbenchSearchResultsList from "@/components/PoWorkbench/search/PoWorkbenchSearchResultsList";

/**
 * Left results column: advanced filter `Slide` + list `Slide`.
 * The list `Slide` uses `appear={false}` to skip the enter animation on first mount (avoids a visible “flash”).
 */
const LEFT_PANE_ROOT_SX = {
  display: "flex",
  flexDirection: "column",
  height: "100%",
  minHeight: 0,
  overflow: "hidden",
  bgcolor: "background.paper",
} as const;

const LEFT_PANE_STACK_HOST_SX = {
  flex: 1,
  minHeight: 0,
  position: "relative",
  overflow: "hidden",
} as const;

const LAYER_BASE_SX = {
  position: "absolute",
  inset: 0,
  display: "flex",
  flexDirection: "column",
  overflow: "hidden",
} as const;

const SLIDE_CONTENT_BASE_SX = {
  height: "100%",
  minHeight: 0,
  flex: 1,
  display: "flex",
  flexDirection: "column",
  position: "relative",
  overflow: "hidden",
} as const;

export interface PoWorkbenchLeftPaneProps {
  isAdvancedSearchOpen: boolean;
  results: readonly PoWorkbenchListRow[];
  totalMatches: number;
  isLoading: boolean;
  isLoadingMore: boolean;
  loadError: string | null;
  hasMore: boolean;
  onLoadMore: () => void;
  selectedId: string | null;
  onSelect: (id: string) => void;
  appliedAdvancedFilters: PoWorkbenchAdvancedFilters;
  onApplyAdvancedFilters: (filters: PoWorkbenchAdvancedFilters) => void;
  onResetAdvancedFilters: () => void;
}

export default function PoWorkbenchLeftPane({
  isAdvancedSearchOpen,
  results,
  totalMatches,
  isLoading,
  isLoadingMore,
  loadError,
  hasMore,
  onLoadMore,
  selectedId,
  onSelect,
  appliedAdvancedFilters,
  onApplyAdvancedFilters,
  onResetAdvancedFilters,
}: PoWorkbenchLeftPaneProps) {
  const theme = useTheme();

  const [draftFilters, setDraftFilters] = useState<PoWorkbenchAdvancedFilters>(
    appliedAdvancedFilters,
  );

  const resetDraftFilters = () => {
    const next = createDefaultAdvancedFilters();
    setDraftFilters(next);
    onResetAdvancedFilters();
  };

  // When `appliedAdvancedFilters` changes in the parent (e.g. after search), mirror into draft fields.
  useEffect(() => {
    setDraftFilters(appliedAdvancedFilters);
  }, [appliedAdvancedFilters]);

  return (
    <Box sx={LEFT_PANE_ROOT_SX}>
      <Box sx={LEFT_PANE_STACK_HOST_SX}>
        {/* Two separate slide mount targets to avoid enter/exit transition overlap. */}
        <Box
          sx={{
            ...LAYER_BASE_SX,
            zIndex: isAdvancedSearchOpen ? 1 : 0,
            pointerEvents: isAdvancedSearchOpen ? "auto" : "none",
          }}
        >
          <Slide
            in={isAdvancedSearchOpen}
            direction="down"
            timeout={220}
            unmountOnExit
          >
            <Box
              sx={{
                ...SLIDE_CONTENT_BASE_SX,
                bgcolor: (t) =>
                  t.palette.mode === "dark" ? "grey.900" : "grey.50",
              }}
            >
              <PoWorkbenchAdvancedSearchPanel
                supplierQuery={draftFilters.supplierQuery}
                orderDateFrom={draftFilters.orderDateFrom}
                orderDateTo={draftFilters.orderDateTo}
                etaDateFrom={draftFilters.etaDateFrom}
                etaDateTo={draftFilters.etaDateTo}
                reportStatus={draftFilters.reportStatus}
                receiveStatus={draftFilters.receiveStatus}
                onSupplierQueryChange={(next) =>
                  setDraftFilters((prev) => ({ ...prev, supplierQuery: next }))
                }
                onOrderDateFromChange={(next) =>
                  setDraftFilters((prev) => ({ ...prev, orderDateFrom: next }))
                }
                onOrderDateToChange={(next) =>
                  setDraftFilters((prev) => ({ ...prev, orderDateTo: next }))
                }
                onEtaDateFromChange={(next) =>
                  setDraftFilters((prev) => ({ ...prev, etaDateFrom: next }))
                }
                onEtaDateToChange={(next) =>
                  setDraftFilters((prev) => ({ ...prev, etaDateTo: next }))
                }
                onReportStatusChange={(next) =>
                  setDraftFilters((prev) => ({ ...prev, reportStatus: next }))
                }
                onReceiveStatusChange={(next) =>
                  setDraftFilters((prev) => ({ ...prev, receiveStatus: next }))
                }
                onApply={() => onApplyAdvancedFilters(draftFilters)}
                onReset={resetDraftFilters}
              />
            </Box>
          </Slide>
        </Box>

        <Box
          sx={{
            ...LAYER_BASE_SX,
            zIndex: isAdvancedSearchOpen ? 0 : 1,
            pointerEvents: isAdvancedSearchOpen ? "none" : "auto",
          }}
        >
          {/* `appear={false}`: skip enter transition on first mount so the list does not "flash" on load. */}
          <Slide
            in={!isAdvancedSearchOpen}
            direction="up"
            timeout={220}
            unmountOnExit
            appear={false}
          >
            <Box sx={SLIDE_CONTENT_BASE_SX}>
              <PoWorkbenchSearchResultsList
                results={results}
                totalMatches={totalMatches}
                isLoading={isLoading}
                isLoadingMore={isLoadingMore}
                loadError={loadError}
                hasMore={hasMore}
                onLoadMore={onLoadMore}
                selectedId={selectedId}
                onSelect={onSelect}
                theme={theme}
              />
            </Box>
          </Slide>
        </Box>
      </Box>
    </Box>
  );
}
