"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, 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";

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[];
};

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

  const pathname = usePathname();
  const router = useRouter();
  const [selectedId, setSelectedId] = useState<number | null>(null);

  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) => {
    router.push(`/po/edit?id=${item.poId}&selectedIds=${item.poId}&polId=${item.polId}&stockInLineId=${item.stockInLineId}`);
  }, [router])

  // 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: "poCode",
        label: t("Po Code"),
        align: "left",
        headerAlign: "left",
        sx: { width: "15%", minWidth: 100 },
      },
      {
        name: "recordDate",
        label: t("escalated date"),
        align: "right",
        headerAlign: "right",
        sx: { width: "10%", minWidth: 100 },
        renderCell: (params) => {
          return arrayToDateString(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: "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 date"),
        align: "right",
        headerAlign: "right",
        sx: { width: "10%", minWidth: 100 },
        renderCell: (params) => {
          return arrayToDateString(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={items}
      columns={getColumnByType(type)}
      isAutoPaging={false}
    />
  )
};

export default EscalationLogTable;
