"use client";

import {
  Box,
  Button,
  Stack,
  TextField,
  Typography,
} from "@mui/material";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/navigation";
import {
  fetchALLPickOrderLineLotDetails,
  updateStockOutLineStatus,
  createStockOutLine,
} from "@/app/api/pickOrder/actions";
import { fetchNameList, NameList } from "@/app/api/user/actions";
import {
  FormProvider,
  useForm,
} from "react-hook-form";
import SearchBox, { Criterion } from "../SearchBox";
import { CreateStockOutLine } from "@/app/api/pickOrder/actions";
import { updateInventoryLotLineQuantities } from "@/app/api/inventory/actions";
import QrCodeIcon from '@mui/icons-material/QrCode';
import { useQrCodeScannerContext } from '../QrCodeScannerProvider/QrCodeScannerProvider';
import CombinedLotTable from './CombinedLotTable';
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig"; // ✅ Import the custom session type

interface Props {
  filterArgs: Record<string, any>;
}

const PickExecution: React.FC<Props> = ({ filterArgs }) => {
  const { t } = useTranslation("pickOrder");
  const router = useRouter();
  const { data: session } = useSession() as { data: SessionWithTokens | null }; // ✅ Cast to custom type
  
  // ✅ Get current user ID from session with proper typing
  const currentUserId = session?.id ? parseInt(session.id) : undefined;
  
  // ✅ Combined approach states
  const [combinedLotData, setCombinedLotData] = useState<any[]>([]);
  const [combinedDataLoading, setCombinedDataLoading] = useState(false);
  const [originalCombinedData, setOriginalCombinedData] = useState<any[]>([]);
  
  // ✅ QR Scanner context
  const { values: qrValues, isScanning, startScan, stopScan, resetScan } = useQrCodeScannerContext();
  
  // ✅ QR scan input states
  const [qrScanInput, setQrScanInput] = useState<string>('');
  const [qrScanError, setQrScanError] = useState<boolean>(false);
  const [qrScanSuccess, setQrScanSuccess] = useState<boolean>(false);
  
  // ✅ Pick quantity states
  const [pickQtyData, setPickQtyData] = useState<Record<string, number>>({});
  
  // ✅ Search states
  const [searchQuery, setSearchQuery] = useState<Record<string, any>>({});

  // ✅ Add pagination state
  const [paginationController, setPaginationController] = useState({
    pageNum: 0,
    pageSize: 10,
  });

  // ✅ Keep only essential states
  const [usernameList, setUsernameList] = useState<NameList[]>([]);

  const formProps = useForm();
  const errors = formProps.formState.errors;

  // ✅ Start QR scanning on component mount
  useEffect(() => {
    startScan();
    return () => {
      stopScan();
      resetScan();
    };
  }, [startScan, stopScan, resetScan]);

  // ✅ Fetch all combined lot data - Updated to use current user ID
  const fetchAllCombinedLotData = useCallback(async (userId?: number) => {
    setCombinedDataLoading(true);
    try {
      // ✅ Use passed userId or current user ID
      const userIdToUse = userId || currentUserId;
      const allLotDetails = await fetchALLPickOrderLineLotDetails(userIdToUse);
      console.log("All combined lot details:", allLotDetails);
      setCombinedLotData(allLotDetails);
      setOriginalCombinedData(allLotDetails); // Store original for filtering
    } catch (error) {
      console.error("Error fetching combined lot data:", error);
      setCombinedLotData([]);
      setOriginalCombinedData([]);
    } finally {
      setCombinedDataLoading(false);
    }
  }, [currentUserId]); // ✅ Add currentUserId as dependency


  // ✅ Load data on component mount - Now uses current user ID
  useEffect(() => {
    fetchAllCombinedLotData(); // This will now use currentUserId
  }, [fetchAllCombinedLotData]);

  // ✅ Handle QR code submission for matched lot - FIXED: Handle multiple pick order lines
  const handleQrCodeSubmit = useCallback(async (lotNo: string) => {
    console.log(`✅ Processing QR Code for lot: ${lotNo}`);
    console.log(`🔍 Available lots:`, combinedLotData.map(lot => lot.lotNo));
    
    // Find ALL matching lots (same lot number can be used by multiple pick order lines)
    const matchingLots = combinedLotData.filter(lot => 
      lot.lotNo === lotNo || 
      lot.lotNo?.toLowerCase() === lotNo.toLowerCase()
    );
    
    if (matchingLots.length === 0) {
      console.error(`❌ Lot not found: ${lotNo}`);
      console.error(`❌ Available lots:`, combinedLotData.map(lot => lot.lotNo));
      setQrScanError(true);
      setQrScanSuccess(false);
      return; 
    }
    
    console.log(`✅ Found ${matchingLots.length} matching lots:`, matchingLots);
    setQrScanError(false);
    
    try {
      let successCount = 0;
      let existsCount = 0;
      let errorCount = 0;
      
      // ✅ Process each matching lot (each pick order line that uses this lot)
      for (const matchingLot of matchingLots) {
        console.log(`🔄 Processing pick order line ${matchingLot.pickOrderLineId} for lot ${lotNo}`);
        
        // ✅ Check if stockOutLineId is null before creating
        if (matchingLot.stockOutLineId) {
          console.log(`✅ Stock out line already exists for line ${matchingLot.pickOrderLineId}`);
          existsCount++;
        } else {
          // Create stock out line for this specific pick order line
          const stockOutLineData: CreateStockOutLine = {
            consoCode: matchingLot.pickOrderCode, // Use pick order code as conso code
            pickOrderLineId: matchingLot.pickOrderLineId,
            inventoryLotLineId: matchingLot.lotId,
            qty: 0.0
          };
          
          console.log(`Creating stock out line for pick order line ${matchingLot.pickOrderLineId}:`, stockOutLineData);
          const result = await createStockOutLine(stockOutLineData);
          console.log(`Create stock out line result for line ${matchingLot.pickOrderLineId}:`, result);
          
          // ✅ Handle different response codes
          if (result && result.code === "EXISTS") {
            console.log(`✅ Stock out line already exists for line ${matchingLot.pickOrderLineId}`);
            existsCount++;
          } else if (result && result.code === "SUCCESS") {
            console.log(`✅ Stock out line created successfully for line ${matchingLot.pickOrderLineId}`);
            successCount++;
          } else {
            console.error(`❌ Unexpected response for line ${matchingLot.pickOrderLineId}:`, result);
            errorCount++;
          }
        }
        
        // Auto-set pick quantity to required quantity for this specific line
        const lotKey = `${matchingLot.pickOrderLineId}-${matchingLot.lotId}`;
        setPickQtyData(prev => ({
          ...prev,
          [lotKey]: matchingLot.requiredQty
        }));
      }
      
      // ✅ Set success state if at least one operation succeeded
      if (successCount > 0 || existsCount > 0) {
        setQrScanSuccess(true);
        setQrScanError(false);
        console.log(`✅ QR Code processing completed: ${successCount} created, ${existsCount} already existed, ${errorCount} errors`);
      } else {
        setQrScanError(true);
        setQrScanSuccess(false);
        console.error(`❌ All operations failed for lot ${lotNo}`);
        return;
      }
      
      // Refresh data
      await fetchAllCombinedLotData();
      
      // Clear input after successful match
      setQrScanInput('');
      
      console.log("Stock out line process completed successfully!");
    } catch (error) {
      console.error("Error creating stock out line:", error);
      setQrScanError(true);
      setQrScanSuccess(false);
    }
  }, [combinedLotData, fetchAllCombinedLotData]);

  // ✅ Process scanned QR codes automatically - FIXED: Only process when data is loaded
  useEffect(() => {
    if (qrValues.length > 0 && combinedLotData.length > 0) {
      const latestQr = qrValues[qrValues.length - 1];
      const qrContent = latestQr.replace(/[{}]/g, '');
      setQrScanInput(qrContent);
      
      // Auto-process the QR code
      handleQrCodeSubmit(qrContent);
    }
  }, [qrValues, combinedLotData, handleQrCodeSubmit]);

  // ✅ Handle manual input submission
  const handleManualInputSubmit = useCallback(() => {
    if (qrScanInput.trim() !== '') {
      handleQrCodeSubmit(qrScanInput.trim());
    }
  }, [qrScanInput, handleQrCodeSubmit]);

  // ✅ Handle pick quantity change - FIXED: Better input handling
  const handlePickQtyChange = useCallback((lotKey: string, value: number | string) => {
    // ✅ Handle empty string as 0
    if (value === '' || value === null || value === undefined) {
      setPickQtyData(prev => ({
        ...prev,
        [lotKey]: 0
      }));
      return;
    }
    
    // ✅ Convert to number properly
    const numericValue = typeof value === 'string' ? parseFloat(value) : value;
    
    // ✅ Handle NaN case
    if (isNaN(numericValue)) {
      setPickQtyData(prev => ({
        ...prev,
        [lotKey]: 0
      }));
      return;
    }
    
    setPickQtyData(prev => ({
      ...prev,
      [lotKey]: numericValue
    }));
  }, []);

  // ✅ Handle submit pick quantity
  const handleSubmitPickQty = useCallback(async (lot: any) => {
    const lotKey = `${lot.pickOrderLineId}-${lot.lotId}`;
    const newQty = pickQtyData[lotKey] || 0;
    
    if (!lot.stockOutLineId) {
      console.error("No stock out line found for this lot");
      return;
    }
    
    try {
      // ✅ FIXED: Calculate cumulative quantity
      const currentActualPickQty = lot.actualPickQty || 0;
      const cumulativeQty = currentActualPickQty + newQty;
      
      // ✅ FIXED: Check cumulative quantity against required quantity
      let newStatus = 'partially_completed';
      
      if (cumulativeQty >= lot.requiredQty) {
        newStatus = 'completed';
      }
      
      console.log(`=== PICK QUANTITY SUBMISSION DEBUG ===`);
      console.log(`Lot: ${lot.lotNo}`);
      console.log(`Required Qty: ${lot.requiredQty}`);
      console.log(`Current Actual Pick Qty: ${currentActualPickQty}`);
      console.log(`New Submitted Qty: ${newQty}`);
      console.log(`Cumulative Qty: ${cumulativeQty}`);
      console.log(`New Status: ${newStatus}`);
      console.log(`=====================================`);
      
      await updateStockOutLineStatus({
        id: lot.stockOutLineId,
        status: newStatus,
        qty: cumulativeQty  // ✅ Submit the cumulative quantity
      });
      
      // Update inventory
      if (newQty > 0) {
        await updateInventoryLotLineQuantities({
          inventoryLotLineId: lot.lotId,
          qty: newQty,  // ✅ Only update inventory with the new quantity
          status: 'available',
          operation: 'pick'
        });
      }
      
      // Refresh data
      await fetchAllCombinedLotData();
      console.log("Pick quantity submitted successfully!");
    } catch (error) {
      console.error("Error submitting pick quantity:", error);
    }
  }, [pickQtyData, fetchAllCombinedLotData]);

  // ✅ Handle reject lot
  const handleRejectLot = useCallback(async (lot: any) => {
    if (!lot.stockOutLineId) {
      console.error("No stock out line found for this lot");
      return;
    }
  
    try {
      await updateStockOutLineStatus({
        id: lot.stockOutLineId,
        status: 'rejected',
        qty: 0
      });
      
      // Refresh data
      await fetchAllCombinedLotData();
      console.log("Lot rejected successfully!");
    } catch (error) {
      console.error("Error rejecting lot:", error);
    }
  }, [fetchAllCombinedLotData]);

  // ✅ Search criteria
  const searchCriteria: Criterion<any>[] = [
    {
      label: t("Pick Order Code"),
      paramName: "pickOrderCode",
      type: "text",
    },
      {
        label: t("Item Code"),
        paramName: "itemCode",
        type: "text",
      },
      {
        label: t("Item Name"),
        paramName: "itemName",
        type: "text",
      },
      {
      label: t("Lot No"),
      paramName: "lotNo",
      type: "text",
    },
  ];

  // ✅ Search handler
  const handleSearch = useCallback((query: Record<string, any>) => {
    setSearchQuery({ ...query });
    console.log("Search query:", query);

    if (!originalCombinedData) return;

    const filtered = originalCombinedData.filter((lot: any) => {
      const pickOrderCodeMatch = !query.pickOrderCode || 
        lot.pickOrderCode?.toLowerCase().includes((query.pickOrderCode || "").toLowerCase());
      
        const itemCodeMatch = !query.itemCode || 
        lot.itemCode?.toLowerCase().includes((query.itemCode || "").toLowerCase());
        
        const itemNameMatch = !query.itemName || 
        lot.itemName?.toLowerCase().includes((query.itemName || "").toLowerCase());
      
      const lotNoMatch = !query.lotNo || 
        lot.lotNo?.toLowerCase().includes((query.lotNo || "").toLowerCase());
      
      return pickOrderCodeMatch && itemCodeMatch && itemNameMatch && lotNoMatch;
    });
    
    setCombinedLotData(filtered);
    console.log("Filtered lots count:", filtered.length);
  }, [originalCombinedData]);

  // ✅ Reset handler
  const handleReset = useCallback(() => {
    setSearchQuery({});
    if (originalCombinedData) {
      setCombinedLotData(originalCombinedData);
    }
  }, [originalCombinedData]);

  // ✅ Pagination handlers
  const handlePageChange = useCallback((event: unknown, newPage: number) => {
    setPaginationController(prev => ({
      ...prev,
      pageNum: newPage,
    }));
  }, []);

  const handlePageSizeChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const newPageSize = parseInt(event.target.value, 10);
    setPaginationController({
      pageNum: 0,
      pageSize: newPageSize,
    });
  }, []);

  return (
    <FormProvider {...formProps}>
      <Stack spacing={2}>
        {/* Search Box */}
        <Box>
          <SearchBox 
            criteria={searchCriteria} 
            onSearch={handleSearch} 
            onReset={handleReset} 
          />
        </Box>

        {/* Combined Lot Table with QR Scan Input */}
        <Box>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Typography variant="h6" gutterBottom sx={{ mb: 0 }}>
              {t("All Pick Order Lots")}
            </Typography>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <TextField
                size="small"
                value={qrScanInput}
                onChange={(e) => setQrScanInput(e.target.value)}
                onKeyPress={(e) => {
                  if (e.key === 'Enter') {
                    handleManualInputSubmit();
                  }
                }}
                error={qrScanError}
                color={qrScanSuccess ? 'success' : undefined}
                helperText={
                  qrScanError 
                    ? t("Lot number not found") 
                    : qrScanSuccess 
                      ? t("Lot processed successfully") 
                      : t("Enter lot number or scan QR code")
                }
                placeholder={t("Enter lot number...")}
                sx={{ minWidth: '250px' }}
                InputProps={{
                  startAdornment: <QrCodeIcon sx={{ mr: 1, color: isScanning ? 'primary.main' : 'text.secondary' }} />,
                }}
              />
              <Button
                variant="outlined"
                onClick={handleManualInputSubmit}
                disabled={!qrScanInput.trim()}
                size="small"
              >
                {t("Submit")}
              </Button>
            </Box>
          </Box>
          
          <CombinedLotTable
            combinedLotData={combinedLotData}
            combinedDataLoading={combinedDataLoading}
            pickQtyData={pickQtyData}
            paginationController={paginationController}
            onPickQtyChange={handlePickQtyChange}
            onSubmitPickQty={handleSubmitPickQty}
            onRejectLot={handleRejectLot}
            onPageChange={handlePageChange}
            onPageSizeChange={handlePageSizeChange}
          />
        </Box>
      </Stack>
    </FormProvider>
  );
};

export default PickExecution;