"use client";
import React, { useCallback, useEffect, useState } from "react";
import {
  Box,
  Button,
  Stack,
  Typography,
  Chip,
  CircularProgress,
  TablePagination,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Tooltip,
} from "@mui/material";
import QrCodeIcon from '@mui/icons-material/QrCode';
import { useTranslation } from "react-i18next";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
import dayjs from "dayjs";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { OUTPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import {
  fetchJoForPrintQrCode,
  JobOrderListForPrintQrCodeResponse,
  printFGStockInLabel,
  PrintFGStockInLabelRequest,
} from "@/app/api/jo/actions";
import { PrinterCombo } from "@/app/api/settings/printer";

interface FinishedQcJobOrderListProps {
  printerCombo: PrinterCombo[];
  selectedPrinter: PrinterCombo | null;
}

const PER_PAGE = 10;

const FinishedQcJobOrderList: React.FC<FinishedQcJobOrderListProps> = ({ 
  printerCombo, 
  selectedPrinter,
}) => {
  const { t } = useTranslation(["common"]);
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  const [loading, setLoading] = useState(false);
  const [jobOrders, setJobOrders] = useState<JobOrderListForPrintQrCodeResponse[]>([]);
  const [page, setPage] = useState(0);
  const [isPrinting, setIsPrinting] = useState(false);
  const [printingId, setPrintingId] = useState<number | null>(null);
  const [selectedDate, setSelectedDate] = useState<dayjs.Dayjs>(dayjs());

  const fetchJobOrders = useCallback(async () => {
    setLoading(true);
    try {
      const dateParam = selectedDate.format("YYYY-MM-DD");
      const data = await fetchJoForPrintQrCode(dateParam);
      setJobOrders(data || []);
      setPage(0);
    } catch (e) {
      console.error(e);
      setJobOrders([]);
    } finally {
      setLoading(false);
    }
  }, [selectedDate]);



  useEffect(() => {
    fetchJobOrders();
  }, [fetchJobOrders]);

  const handlePrint = useCallback(async (jobOrder: JobOrderListForPrintQrCodeResponse) => {
    if (!selectedPrinter) {
      alert(t("Please select a printer"));
      return;
    }

    // Use stockInLineId from the response (assuming backend returns it)
    // If the backend still returns stockOutLineId, you may need to update the interface
    const stockInLineId = (jobOrder as any).stockInLineId || jobOrder.stockOutLineId;
    
    if (!stockInLineId) {
      alert(t("Invalid Stock In Line Id"));
      return;
    }

    try {
      setIsPrinting(true);
      setPrintingId(jobOrder.id);
      
      const data: PrintFGStockInLabelRequest = {
        stockInLineId: stockInLineId,
        printerId: selectedPrinter.id,
        printQty: 1 // Default to 1
      };
      
      const response = await printFGStockInLabel(data);
      
      if (response) {
        console.log("Print response:", response);
        alert(t("Print job sent successfully"));
      }
    } catch (error: any) {
      console.error("Error printing:", error);
      alert(t(`Print failed: ${error?.message || "Unknown error"}`));
    } finally {
      setIsPrinting(false);
      setPrintingId(null);
    }
  }, [selectedPrinter, t]);

  const startIdx = page * PER_PAGE;
  const paged = jobOrders.slice(startIdx, startIdx + PER_PAGE);

  return (
    <Box>
      {/* Date Selector */}
      <Stack direction="row" spacing={2} sx={{ mb: 2, alignItems: 'flex-start' }}>
        <Box sx={{ maxWidth: 300 }}>
          <LocalizationProvider dateAdapter={AdapterDayjs}>
            <DatePicker
              label={t("Select Date")}
              value={selectedDate}
              onChange={(newValue) => {
                if (newValue) setSelectedDate(newValue);
              }}
              format="YYYY-MM-DD"
              slotProps={{
                textField: { fullWidth: true, size: "small" },
              }}
            />
          </LocalizationProvider>
        </Box>
      </Stack>

      {loading ? (
        <Box sx={{ display: "flex", justifyContent: "center", p: 3 }}>
          <CircularProgress />
        </Box>
      ) : (
        <Box>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            {t("Total finished QC job orders")}: {jobOrders.length}
          </Typography>

          <TableContainer component={Paper} sx={{ boxShadow: 2 }}>
            <Table sx={{ minWidth: 650 }}>
              <TableHead>
                <TableRow sx={{ bgcolor: "grey.50" }}>
                  <TableCell sx={{ fontWeight: "bold" }}>{t("Code")}</TableCell>
                  <TableCell sx={{ fontWeight: "bold" }}>{t("Name")}</TableCell>
                  <TableCell sx={{ fontWeight: "bold" }}>{t("Required Qty")}</TableCell>
                  <TableCell sx={{ fontWeight: "bold" }}>{t("Finished Time")}</TableCell>
                  <TableCell sx={{ fontWeight: "bold" }} align="center">{t("Action")}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {paged.map((jobOrder) => {
                  const statusColor = jobOrder.stockOutLineStatus === "completed" 
                    ? "success" 
                    : "default";

                  const finishedTimeDisplay = jobOrder.finihedTime
                    ? dayjs(jobOrder.finihedTime).format(OUTPUT_DATE_FORMAT)
                    : "-";

                  const isCurrentlyPrinting = isPrinting && printingId === jobOrder.id;

                  return (
                    <TableRow
                      key={jobOrder.id}
                      sx={{
                        "&:last-child td, &:last-child th": { border: 0 },
                        "&:hover": { bgcolor: "grey.50" },
                      }}
                    >
                      <TableCell component="th" scope="row">
                        {jobOrder.code}
                      </TableCell>
                      <TableCell>{jobOrder.name}</TableCell>
                      <TableCell>{jobOrder.reqQty}</TableCell>

                      <TableCell>{finishedTimeDisplay}</TableCell>
                      <TableCell align="center">
                        <Tooltip title={t("Print QR Code")}>
                          <IconButton
                            color="primary"
                            onClick={() => handlePrint(jobOrder)}
                            disabled={isPrinting || printerCombo.length <= 0 || !selectedPrinter}
                            size="small"
                          >
                            {isCurrentlyPrinting ? (
                              <CircularProgress size={20} />
                            ) : (
                              <QrCodeIcon />
                            )}
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>

          {jobOrders.length > 0 && (
            <TablePagination
              component="div"
              count={jobOrders.length}
              page={page}
              rowsPerPage={PER_PAGE}
              onPageChange={(e, p) => setPage(p)}
              rowsPerPageOptions={[PER_PAGE]}
            />
          )}
        </Box>
      )}
    </Box>
  );
};

export default FinishedQcJobOrderList;