"use client";

import { Box, CircularProgress } from "@mui/material";
import { useCallback, useEffect, useMemo, useState } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
import {
  fetchAllPickOrderLotsHierarchicalWorkbench,
} from "@/app/api/pickOrder/actions";
import WorkbenchFloorLanePanel from "./WorkbenchFloorLanePanel";
import WorkbenchGoodPickExecutionDetail from "./WorkbenchGoodPickExecutionDetail";
import type { WorkbenchLanePanelPrefs } from "./workbenchLanePanelPrefs";

export type DoWorkbenchPickShellLaneMode = "normal" | "etra";

type DoWorkbenchPickShellProps = {
  /** Tab 0: normal 2F/4F lane grid; tab 1: Etra-only lane grid */
  laneMode?: DoWorkbenchPickShellLaneMode;
  lanePanelPrefs: WorkbenchLanePanelPrefs;
  onLanePanelPrefsChange: (prefs: WorkbenchLanePanelPrefs) => void;
};

/**
 * FG workbench: 未指派顯示樓層／車線指派；已指派顯示揀貨明細（workbench API）。
 */
const DoWorkbenchPickShell: React.FC<DoWorkbenchPickShellProps> = ({
  laneMode = "normal",
  lanePanelPrefs,
  onLanePanelPrefsChange,
}) => {
  const { data: session, status } = useSession() as {
    data: SessionWithTokens | null;
    status: "loading" | "authenticated" | "unauthenticated";
  };
  const currentUserId = session?.id ? parseInt(session.id, 10) : undefined;
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [showDetail, setShowDetail] = useState(false);
  const [viewLoading, setViewLoading] = useState(true);
  const filterArgs = useMemo(() => ({}), []);

  const refreshWorkbenchView = useCallback(async () => {
    if (!currentUserId) {
      setShowDetail(false);
      setViewLoading(false);
      return;
    }
    setViewLoading(true);
    try {
      const data = await fetchAllPickOrderLotsHierarchicalWorkbench(currentUserId);
      const ticketStatus = String(data?.ticketStatus ?? "").trim().toLowerCase();
      const hasDetailData = Boolean(data?.fgInfo && Array.isArray(data?.pickOrders) && data.pickOrders.length > 0);
      const shouldShowDetail = ticketStatus !== "completed" && (ticketStatus.length > 0 || hasDetailData);
      setShowDetail(shouldShowDetail);
    } catch {
      setShowDetail(false);
    } finally {
      setViewLoading(false);
    }
  }, [currentUserId]);

  useEffect(() => {
    if (status === "loading") return;
    if (status !== "authenticated" || !currentUserId) {
      setViewLoading(false);
      setShowDetail(false);
      return;
    }
    void refreshWorkbenchView();
  }, [status, currentUserId, refreshWorkbenchView]);

  useEffect(() => {
    const onAssigned = () => {
      void refreshWorkbenchView();
    };
    window.addEventListener("pickOrderAssigned", onAssigned);
    return () => window.removeEventListener("pickOrderAssigned", onAssigned);
  }, [refreshWorkbenchView]);

  const onWorkbenchHierarchyEmpty = useCallback(() => {
    void refreshWorkbenchView();
  }, [refreshWorkbenchView]);

  const goNormalAssignTab = useCallback(() => {
    const p = new URLSearchParams(searchParams.toString());
    p.set("tab", "0");
    const qs = p.toString();
    router.replace(qs ? `${pathname}?${qs}` : `${pathname}?tab=0`, { scroll: false });
  }, [pathname, router, searchParams]);

  if (status === "loading") {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", p: 3, width: "100%" }}>
        <CircularProgress />
      </Box>
    );
  }

  const showAssignmentSpinner = viewLoading;

  return (
    <Box sx={{ width: "100%" }}>
      {showAssignmentSpinner ? (
        <Box sx={{ display: "flex", justifyContent: "center", p: 3 }}>
          <CircularProgress />
        </Box>
      ) : !showDetail ? (
        <WorkbenchFloorLanePanel
          onPickOrderAssigned={() => void refreshWorkbenchView()}
          etraOnly={laneMode === "etra"}
          onRequestNormalLaneTab={laneMode === "etra" ? goNormalAssignTab : undefined}
          lanePanelPrefs={lanePanelPrefs}
          onLanePanelPrefsChange={onLanePanelPrefsChange}
        />
      ) : (
        <WorkbenchGoodPickExecutionDetail
          filterArgs={filterArgs}
          onWorkbenchHierarchyEmpty={onWorkbenchHierarchyEmpty}
        />
      )}
    </Box>
  );
};

export default DoWorkbenchPickShell;
