"use client";
import React, { useState, useEffect, useCallback } from "react";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
import { Box, Tabs, Tab, Stack, Typography, Autocomplete, TextField } from "@mui/material";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import QcStockInModal from "@/components/Qc/QcStockInModal";
import ProductionProcessList, {
  createDefaultProductionProcessListPersistedState,
} from "@/components/ProductionProcess/ProductionProcessList";
import ProductionProcessJobOrderDetail from "@/components/ProductionProcess/ProductionProcessJobOrderDetail";
import JobPickExecutionsecondscan from "@/components/Jodetail/JobPickExecutionsecondscan";
import JobProcessStatus from "@/components/ProductionProcess/JobProcessStatus";
import OperatorKpiDashboard from "@/components/ProductionProcess/OperatorKpiDashboard";
import EquipmentStatusDashboard from "@/components/ProductionProcess/EquipmentStatusDashboard";
import DrinkProductionQtyDashboard from "@/components/ProductionProcess/DrinkProductionQtyDashboard";
import JobOrderOpsTable from "@/components/ProductionProcess/JobOrderOpsTable";
import type { PrinterCombo } from "@/app/api/settings/printer";
import { useTranslation } from "react-i18next";

interface ProductionProcessPageProps {
  printerCombo: PrinterCombo[];
}

const STORAGE_KEY = 'productionProcess_selectedMatchingStock';

/**
 * FP-MTMS Version Checklist | Functions Ref. No. 26 | v1.0.0 | 2026-07-20
 * FP-MTMS Version Checklist | Functions Ref. No. 47 | v1.0.2 | 2026-08-05
 */
const ProductionProcessPage: React.FC<ProductionProcessPageProps> = ({ printerCombo }) => {
  const { t } = useTranslation(["common", "productionProcess"]);
  const [selectedProcessId, setSelectedProcessId] = useState<number | null>(null);
  const [selectedMatchingStock, setSelectedMatchingStock] = useState<{
    jobOrderId: number;
    productProcessId: number;
    pickOrderId: number;
  } | null>(null);
  /** 0 = Production Process list; 1 = JO ops table; 2..5 = dashboards */
  const [tabIndex, setTabIndex] = useState(0);
  const [productionListState, setProductionListState] = useState(() => ({
    ...createDefaultProductionProcessListPersistedState(),
  }));
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  const sessionToken = session as SessionWithTokens | null;
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const router = useRouter();
  const [linkQcOpen, setLinkQcOpen] = useState(false);
  const [linkQcSilId, setLinkQcSilId] = useState<number | null>(null);

  const [selectedPrinter, setSelectedPrinter] = useState<PrinterCombo | null>(
    printerCombo && printerCombo.length > 0 ? printerCombo[0] : null
  );

  useEffect(() => {
    if (typeof window !== 'undefined') {
      try {
        const saved = sessionStorage.getItem(STORAGE_KEY);
        if (saved) {
          const parsed = JSON.parse(saved);
          if (parsed && typeof parsed.jobOrderId === 'number' && typeof parsed.productProcessId === 'number') {
            setSelectedMatchingStock(parsed);
          }
        }
      } catch (error) {
        console.error("Error restoring selectedMatchingStock:", error);
        sessionStorage.removeItem(STORAGE_KEY);
      }
    }
  }, []);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      if (selectedMatchingStock) {
        sessionStorage.setItem(STORAGE_KEY, JSON.stringify(selectedMatchingStock));
      } else {
        sessionStorage.removeItem(STORAGE_KEY);
      }
    }
  }, [selectedMatchingStock]);

  const handleBackFromSecondScan = useCallback(() => {
    setSelectedMatchingStock(null);
    if (typeof window !== 'undefined') {
      sessionStorage.removeItem(STORAGE_KEY);
    }
  }, []);

  const handleTabChange = useCallback((event: React.SyntheticEvent, newValue: number) => {
    setTabIndex(newValue);
  }, []);

  const openStockInLineIdQ = searchParams.get("openStockInLineId");

  /** Deep link: /productionProcess?openStockInLineId=… → list tab pending_qc + FG QC modal */
  useEffect(() => {
    if (!openStockInLineIdQ) {
      setLinkQcOpen(false);
      setLinkQcSilId(null);
      return;
    }
    const id = parseInt(openStockInLineIdQ, 10);
    if (!Number.isFinite(id) || id <= 0) return;
    setSelectedProcessId(null);
    setSelectedMatchingStock(null);
    setTabIndex(0);
    setProductionListState((prev) => ({
      ...prev,
      pickBucket: "pending_qc",
      page: 0,
    }));
    setLinkQcSilId(id);
    setLinkQcOpen(true);
  }, [openStockInLineIdQ]);

  const closeLinkQc = useCallback(() => {
    setLinkQcOpen(false);
    setLinkQcSilId(null);
    const p = new URLSearchParams(searchParams.toString());
    p.delete("openStockInLineId");
    const q = p.toString();
    router.replace(q ? `${pathname}?${q}` : pathname, { scroll: false });
  }, [pathname, router, searchParams]);

  const listTab = String(productionListState.pickBucket || "needs_action");
  const showPrinterBar = tabIndex === 0 && listTab === "pending_qc";

  if (selectedMatchingStock) {
    return (
      <JobPickExecutionsecondscan
        filterArgs={{ 
          jobOrderId: selectedMatchingStock.jobOrderId,
          pickOrderId: selectedMatchingStock.pickOrderId,
        }}
        onBack={handleBackFromSecondScan}
      />
    );
  }
  
  if (selectedProcessId !== null) {
    return (
      <ProductionProcessJobOrderDetail
        jobOrderId={selectedProcessId}
        initialTabIndex={2}
        onBack={() => setSelectedProcessId(null)}
      />
    );
  }

  return (
    <>
    <Box>
      {showPrinterBar && (
        <Box sx={{ 
          p: 1,
          borderBottom: '1px solid #e0e0e0',
          minHeight: 'auto',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'flex-end',
          gap: 2,
          flexWrap: 'wrap',
        }}>
          <Stack
            direction="row"
            spacing={2}
            sx={{
              alignItems: 'center',
              flexWrap: 'wrap',
              rowGap: 1,
            }}
          >
            <Typography variant="body2" sx={{ minWidth: 'fit-content', mr: 1.5 }}>
              {t("Select Printer")}:
            </Typography>
            <Autocomplete
              disableClearable
              options={printerCombo || []}
              getOptionLabel={(option) =>
                option.name || option.label || option.code || `Printer ${option.id}`
              }
              value={selectedPrinter || undefined}
              onChange={(_, newValue) => setSelectedPrinter(newValue)}
              sx={{ minWidth: 200 }}
              size="small"
              renderInput={(params) => (
                <TextField 
                  {...params} 
                  placeholder={t("Printer")}
                  inputProps={{
                    ...params.inputProps,
                    readOnly: true,
                  }}
                />
              )}
            />
          </Stack>
        </Box>
      )}

      <Tabs value={tabIndex} onChange={handleTabChange} sx={{ mb: 2 }}>
        <Tab label={t("Production Process")} />
        <Tab label={t("Job Order Ops Table")} />
        <Tab label={t("Job Process Status Dashboard")} />
        <Tab label={t("Operator KPI Dashboard")} />
        <Tab label={t("Production Equipment Status Dashboard")} />
        <Tab label={t("Drink Production Qty Dashboard")} />
      </Tabs>

      {tabIndex === 0 && (
        <ProductionProcessList
          printerCombo={selectedPrinter ? [selectedPrinter] : printerCombo}
          listPersistedState={productionListState}
          onListPersistedStateChange={setProductionListState}
          onSelectProcess={(jobOrderId) => {
            const id = jobOrderId ?? null;
            if (id !== null) {
              setSelectedProcessId(id);
            }
          }}
          onSelectMatchingStock={(jobOrderId, productProcessId,pickOrderId) => {
            setSelectedMatchingStock({ 
              jobOrderId: jobOrderId || 0, 
              productProcessId: productProcessId || 0 ,
              pickOrderId: pickOrderId || 0
            });
          }}
        />
      )}

      {tabIndex === 1 && (
        <JobOrderOpsTable
          printerCombo={selectedPrinter ? [selectedPrinter] : printerCombo}
          onSelectProcess={(jobOrderId) => {
            if (jobOrderId != null) setSelectedProcessId(jobOrderId);
          }}
        />
      )}

      {tabIndex === 2 && (
        <JobProcessStatus />
      )}
      {tabIndex === 3 && (
        <OperatorKpiDashboard />
      )}
      {tabIndex === 4 && (
        <EquipmentStatusDashboard />
      )}
      {tabIndex === 5 && (
        <DrinkProductionQtyDashboard />
      )}
    </Box>
    <QcStockInModal
      session={sessionToken}
      open={Boolean(linkQcOpen && linkQcSilId != null && linkQcSilId > 0)}
      onClose={closeLinkQc}
      inputDetail={linkQcSilId != null && linkQcSilId > 0 ? { id: linkQcSilId } : undefined}
      printerCombo={printerCombo}
      warehouse={[]}
      printSource="productionProcess"
      uiMode="default"
    />
    </>
  );
};

export default ProductionProcessPage;
