"use client"

import { Box, Card, CardActionArea, CardContent, CardHeader, Grid, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography } from "@mui/material";
import { useRouter } from "next/navigation";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { usePathname } from "next/navigation";
import { useTranslation } from "react-i18next";
import { EscalationResult } from "@/app/api/escalation";
import { Column } from "@/components/SearchResults";
import SearchResults from "@/components/SearchResults/SearchResults";
import { arrayToDateString, arrayToDateTimeString } from "@/app/utils/formatUtil";
import { CardFilterContext } from "@/components/CollapsibleCard/CollapsibleCard";
import QcStockInModal from "@/components/Qc/QcStockInModal";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
import { StockInLineInput } from "@/app/api/stockIn";
import { PrinterCombo } from "@/app/api/settings/printer";
export type IQCItems = {
  id: number;
  poId: number;
  polId: number;
  stockInLineId: number;
  poCode: string
  itemName: string
  escalationLevel: string
  reason: string
};

type Props = {
  type?: "dashboard" | "qc";
  items: EscalationResult[];
  printerCombo?: PrinterCombo[];
};

const EscalationLogTable: React.FC<Props> = ({
  type = "dashboard", items, printerCombo
}) => {
  const { t } = useTranslation(["dashboard","purchaseOrder"]);
  const CARD_HEADER = t("stock in escalation list")

  const pathname = usePathname();
  const router = useRouter();
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  const sessionToken = session as SessionWithTokens | null;
  const [selectedId, setSelectedId] = useState<number | null>(null);

  const [escalationLogs, setEscalationLogs] = useState<EscalationResult[]>([]);
  const [openModal, setOpenModal] = useState(false);
const [modalInfo, setModalInfo] = useState<StockInLineInput>();
const [modalPrintSource, setModalPrintSource] = useState<"stockIn" | "productionProcess">("stockIn");
  const useCardFilter = useContext(CardFilterContext);
  const showCompleted = useMemo(() => {
    if (type === "dashboard") {
      return useCardFilter.filter;
    } else { return true}
  }, [useCardFilter.filter]);
  
  useEffect(() => {
    if (showCompleted) {
      setEscalationLogs(items);
    } else {
      const filteredEscLog = items.filter(log => log.status == "pending");
      setEscalationLogs(filteredEscLog);
    }
  }, [showCompleted, items])
  /*
  const navigateTo = useCallback(
    (item: EscalationResult) => {
      setSelectedId(item.id);
      console.log(pathname)
      router.replace(`/po/edit?id=${item.poId}&polId=${item.polId}&stockInLineId=${item.stockInLineId}`);
    },
    [router, pathname]
  );
  */

  const onRowClick = useCallback((item: EscalationResult) => {
    if (type !== "dashboard") return;
  
    if (!item.stockInLineId) {
      alert(t("Invalid Stock In Line Id"));
      return;
    }
  
    setModalInfo({
      id: item.stockInLineId,
    });
  
    setModalPrintSource(item.jobOrderId ? "productionProcess" : "stockIn");
    setOpenModal(true);
  }, [type, t]);
  const closeNewModal = useCallback(() => {
    setOpenModal(false);
    setModalInfo(undefined);
  }, []);
  // const handleKeyDown = useCallback(
  //   (e: React.KeyboardEvent, item: EscalationResult) => {
  //     if (e.key === 'Enter' || e.key === ' ') {
  //       e.preventDefault();
  //       navigateTo(item);
  //     }
  //   },
  //   [navigateTo]
  // );

  const base_col = useMemo<Column<EscalationResult>[]>(
    () => [
      {
        name: "qcFailCount",
        label: t("QC Fail Count"),
        align: "right",
        headerAlign: "right",
        sx: { width: "10%", minWidth: 120 },
        renderCell: (params) => {
          return `${params.qcFailCount} / ${params.qcTotalCount}`
        }
      },
      {
        name: "reason",
        label: t("Reason"),
        sx: { width: "30%", minWidth: 150 },
      },
      {
        name: "status",
        label: t("escalationStatus"),
        sx: { width: "10%", minWidth: 150 },
        renderCell: (params) => {
          return t(params.status);
          // return t(`${params.status}`);
        }
      },
    ], [])

  const columns_dashboard = useMemo<Column<EscalationResult>[]>(
    () => [
      {
        name: "submitter",
        label: t("escalateFrom"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: 100 },
      },
      {
        name: "poCode",
        label: t("Po Code/Jo Code"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: 100 },
        renderCell: (params) => {
          return params.jobOrderCode ?? params.poCode ?? "-";
        }
      },
      {
        name: "recordDate",
        label: t("escalated datetime"),
        align: "right",
        headerAlign: "right",
        sx: { width: "10%", minWidth: 100 },
        renderCell: (params) => {
          return arrayToDateTimeString(params.recordDate);
        }
      },
      {
        name: "itemName",
        label: t("Item Name"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: 100 },
      },
      {
        name: "acceptedQty",
        label: t("Received Qty"),
        align: "right",
        headerAlign: "right",
        sx: { width: "5%", minWidth: 100 },
      },
      {
        name: "purchaseUomDesc",
        label: t("Purchase UoM"),
        sx: { width: "15%", minWidth: 120 },
      },
      {
        name: "dnDate",
        label: t("DN Date"),
        sx: { width: "10%", minWidth: 120 },
        renderCell: (params) => {
          return params.dnDate ? arrayToDateString(params.dnDate) : "N/A"
        }
      },
      ...base_col
    ], [])
  
    const columns_qc = useMemo<Column<EscalationResult>[]>(
    () => [
      {
        name: "submitter",
        label: t("escalateFrom"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: 100 },
      },
      {
        name: "handler",
        label: t("Responsible for handling colleagues"),
        sx: { width: "20%", minWidth: 200, maxWidth: 500 },
        renderCell: (params) => {
          const department = params.handlerDepartment;
          const name = params.handlerName;
          const title = params.handlerTitle;
          return (
            (department ? `${department} - ` : "") + name + (title ? ` (${title})` : "")
          );
        }
      },
      {
        name: "recordDate",
        label: t("escalated datetime"),
        align: "right",
        headerAlign: "right",
        sx: { width: "10%", minWidth: 100 },
        renderCell: (params) => {
          return arrayToDateTimeString(params.recordDate);
        }
      },
      {
        name: "acceptedQty",
        label: t("Received Qty"),
        align: "right",
        headerAlign: "right",
        sx: { width: "5%", minWidth: 100 },
      },
      {
        name: "purchaseUomDesc",
        label: t("Purchase UoM"),
        sx: { width: "15%", minWidth: 120 },
      },
      ...base_col
    ], [])

    const getColumnByType = (type : Props['type']) => {
      switch (type) {
        case "qc": return columns_qc;
        default: return columns_dashboard;
      }
    }
  {/* return (
    <TableContainer component={Paper}>
      <Table aria-label="Two column navigable table" size="small">
        <TableHead>
          <TableRow>
            <TableCell>{t("Purchase Order Code")}</TableCell>
            <TableCell>{t("Item Name")}</TableCell>
            <TableCell>{t("Escalation Level")}</TableCell>
            <TableCell>{t("Reason")}</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {items.map((item) => {
            const selected = selectedId === item.id;
            return (
              <TableRow
                key={item.id}
                hover
                selected={selected}
                onClick={() => navigateTo(item)}
                // onKeyDown={(e) => handleKeyDown(e, item)}
                tabIndex={0}
                sx={{ cursor: 'pointer' }}
                // aria-label={`${item.name}, ${item.detail}`}
              >
                <TableCell component="th" scope="row">
                  {item.poCode}
                </TableCell>
                <TableCell>{item.itemName}</TableCell>
                <TableCell>{item.escalationLevel}</TableCell>
                <TableCell>{item.reason}</TableCell>
              </TableRow>
            );
          })}
        </TableBody>
      </Table>
    </TableContainer>
        );*/}
        return (
          <>
            <SearchResults
              onRowClick={onRowClick}
              items={escalationLogs}
              columns={getColumnByType(type)}
              isAutoPaging={false}
            />
        
            <QcStockInModal
              session={sessionToken}
              open={openModal}
              onClose={closeNewModal}
              inputDetail={modalInfo}
              printerCombo={printerCombo || []}
              warehouse={[]}
              printSource="productionProcess"
              uiMode="default"
            />
          </>
  )
  
};

export default EscalationLogTable;
