"use client";

import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Box,
  Button,
  Card,
  CardActions,
  CardContent,
  Chip,
  CircularProgress,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Typography,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import type { PrinterCombo } from "@/app/api/settings/printer";
import { useTranslation } from "react-i18next";
import Swal from "sweetalert2";
import dayjs from "dayjs";
import { OUTPUT_DATE_FORMAT } from "@/app/utils/formatUtil";
import { useSession } from "next-auth/react";
import { SessionWithTokens } from "@/config/authConfig";
import {
  CompletedDoPickOrderResponse,
  fetchCompletedDoPickOrdersWorkbench,
  fetchCompletedDoPickOrdersWorkbenchAll,
} from "@/app/api/pickOrder/actions";
import { printDNWorkbench, printDNLabelsWorkbench, printDNLabelsReprintWorkbench } from "@/app/api/do/actions";
import { fetchWorkbenchCompletedLotDetails } from "@/app/api/doworkbench/actions";
import SearchBox, { Criterion } from "../SearchBox";
import { resolveWorkbenchRecordTargetDate } from "@/utils/workbenchTargetDate";
import { isWorkbenchExtraTicket } from "@/utils/workbenchReleaseType";

type Props = {
  printerCombo: PrinterCombo[];
  listScope?: "mine" | "all";
  a4Printer: PrinterCombo | null;
  labelPrinter: PrinterCombo | null;
  initialTicketNo?: string | null;
  initialTargetDate?: string | null;
  /** When true (Item Tracing `openDetail=1`), auto-open matching ticket detail. */
  openDetail?: boolean;
};

/** FP-MTMS Version Checklist | Functions Ref. No. 20 | v1.0.0 | 2026-07-19 */
const GoodPickExecutionWorkbenchRecord: React.FC<Props> = ({
  printerCombo,
  listScope = "mine",
  a4Printer,
  labelPrinter,
  initialTicketNo,
  initialTargetDate,
  openDetail = false,
}) => {
  const { t } = useTranslation("pickOrder");
  const { data: session } = useSession() as { data: SessionWithTokens | null };
  const currentUserId = session?.id ? parseInt(session.id, 10) : undefined;

  const [loading, setLoading] = useState(false);
  const [records, setRecords] = useState<CompletedDoPickOrderResponse[]>([]);
  const initialSearchTargetDate = useMemo(
    () => resolveWorkbenchRecordTargetDate(initialTargetDate),
    [initialTargetDate],
  );

  const [searchQuery, setSearchQuery] = useState<Record<string, any>>(() => ({
    targetDate: resolveWorkbenchRecordTargetDate(initialTargetDate),
  }));
  const [showDetailView, setShowDetailView] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<CompletedDoPickOrderResponse | null>(null);
  const [detailLotData, setDetailLotData] = useState<any[]>([]);

  const loadData = useCallback(async (searchParams?: {
    targetDate?: string;
    shopName?: string;
    deliveryNoteCode?: string;
    truckLanceCode?: string;
    ticketNo?: string;
  }) => {
    setLoading(true);
    try {
      const data =
        listScope === "all"
          ? await fetchCompletedDoPickOrdersWorkbenchAll(searchParams)
          : currentUserId
            ? await fetchCompletedDoPickOrdersWorkbench(currentUserId, searchParams)
            : [];
      setRecords(data || []);
    } catch (e) {
      console.error("Failed to load workbench completed records:", e);
      setRecords([]);
    } finally {
      setLoading(false);
    }
  }, [currentUserId, listScope]);

  useEffect(() => {
    const targetDate = resolveWorkbenchRecordTargetDate(initialTargetDate);
    const tn = initialTicketNo?.trim() || undefined;
    setSearchQuery((prev) => ({
      ...prev,
      targetDate,
      ...(tn ? { ticketNo: tn } : {}),
    }));
    void loadData({
      targetDate,
      ...(tn ? { ticketNo: tn } : {}),
    });
  }, [loadData, initialTicketNo, initialTargetDate]);

  const searchCriteria: Criterion<any>[] = useMemo(
    () => [
      {
        label: t("Delivery Note Code"),
        paramName: "deliveryNoteCode",
        type: "text",
      },
      {
        label: t("Shop Name"),
        paramName: "shopName",
        type: "text",
      },
      {
        label: t("Truck Lance Code"),
        paramName: "truckLanceCode",
        type: "text",
      },
      {
        label: t("Target Date"),
        paramName: "targetDate",
        type: "date",
        defaultValue: dayjs().format("YYYY-MM-DD"),
        ...(initialTargetDate
          ? { preFilledValue: initialSearchTargetDate }
          : {}),
      },
      {
        label: t("Ticket No"),
        paramName: "ticketNo",
        type: "text",
        ...(initialTicketNo?.trim()
          ? { preFilledValue: initialTicketNo.trim() }
          : {}),
      },
    ],
    [t, initialTicketNo, initialTargetDate, initialSearchTargetDate],
  );

  const handleSearch = useCallback((query: Record<string, any>) => {
    setSearchQuery({ ...query });
    void loadData({
      targetDate: query.targetDate || undefined,
      shopName: query.shopName || undefined,
      deliveryNoteCode: query.deliveryNoteCode || undefined,
      truckLanceCode: query.truckLanceCode || undefined,
      ticketNo: query.ticketNo || undefined,
    });
  }, [loadData]);

  const handleSearchReset = useCallback(() => {
    const today = dayjs().format("YYYY-MM-DD");
    const resetQuery = { targetDate: today };
    setSearchQuery(resetQuery);
    void loadData({ targetDate: today });
  }, [loadData]);

  const searchDateDisplay = useMemo(() => {
    const raw = searchQuery.targetDate;
    if (raw && String(raw).trim() !== "") {
      const d = dayjs(raw);
      return d.isValid() ? d.format(OUTPUT_DATE_FORMAT) : t("All dates");
    }
    return t("All dates");
  }, [searchQuery.targetDate, t]);

  const askNumOfCarton = useCallback(async () => {
    const result = await Swal.fire({
      title: t("Enter the number of cartons: "),
      icon: "info",
      input: "number",
      inputPlaceholder: t("Number of cartons"),
      inputAttributes: {
        min: "1",
        step: "1",
      },
      inputValidator: (value) => {
        if (!value) return t("You need to enter a number");
        if (parseInt(value, 10) < 1) return t("Number must be at least 1");
        return null;
      },
      showCancelButton: true,
      confirmButtonText: t("Confirm"),
      cancelButtonText: t("Cancel"),
      confirmButtonColor: "#8dba00",
      cancelButtonColor: "#F04438",
    });
    if (!result.isConfirmed) return null;
    return parseInt(result.value, 10);
  }, [t]);

  const handlePrintDN = useCallback(
    async (recordId: number) => {
      if (!a4Printer) {
        await Swal.fire({
          position: "bottom-end",
          icon: "warning",
          text: t("Please select a printer first"),
          showConfirmButton: false,
          timer: 1500,
        });
        return;
      }
      const cartonQty = await askNumOfCarton();
      if (!cartonQty) return;
      const response = await printDNWorkbench({
        deliveryOrderPickOrderId: recordId,
        printerId: a4Printer.id,
        printQty: 1,
        isDraft: false,
        numOfCarton: cartonQty,
      });
      if (response.success) {
        await Swal.fire({
          position: "bottom-end",
          icon: "success",
          text: t("Printed Successfully."),
          showConfirmButton: false,
          timer: 1500,
        });
        await loadData();
      }
    },
    [a4Printer, askNumOfCarton, loadData, t],
  );

  const handlePrintLabel = useCallback(
    async (recordId: number) => {
      if (!labelPrinter) {
        await Swal.fire({
          position: "bottom-end",
          icon: "warning",
          text: t("Please select a label printer first"),
          showConfirmButton: false,
          timer: 1500,
        });
        return;
      }
      const cartonQty = await askNumOfCarton();
      if (!cartonQty) return;
      const response = await printDNLabelsWorkbench({
        deliveryOrderPickOrderId: recordId,
        printerId: labelPrinter.id,
        printQty: 1,
        numOfCarton: cartonQty,
      });
      if (response.success) {
        await Swal.fire({
          position: "bottom-end",
          icon: "success",
          text: t("Printed Successfully."),
          showConfirmButton: false,
          timer: 1500,
        });
        await loadData();
      }
    },
    [askNumOfCarton, labelPrinter, loadData, t],
  );

  const handlePrintBoth = useCallback(
    async (recordId: number) => {
      if (!a4Printer || !labelPrinter) {
        await Swal.fire({
          position: "bottom-end",
          icon: "warning",
          text: t("Please select a printer first"),
          showConfirmButton: false,
          timer: 1500,
        });
        return;
      }
      const cartonQty = await askNumOfCarton();
      if (!cartonQty) return;
      const [labelRes, dnRes] = await Promise.all([
        printDNLabelsWorkbench({
          deliveryOrderPickOrderId: recordId,
          printerId: labelPrinter.id,
          printQty: 1,
          numOfCarton: cartonQty,
        }),
        printDNWorkbench({
          deliveryOrderPickOrderId: recordId,
          printerId: a4Printer.id,
          printQty: 1,
          isDraft: false,
          numOfCarton: cartonQty,
        }),
      ]);
      if (labelRes.success && dnRes.success) {
        await Swal.fire({
          position: "bottom-end",
          icon: "success",
          text: t("Printed Successfully."),
          showConfirmButton: false,
          timer: 1500,
        });
        await loadData();
      }
    },
    [a4Printer, askNumOfCarton, labelPrinter, loadData, t],
  );
  const handleLabelReprint = useCallback(async (doPickOrder: CompletedDoPickOrderResponse) => {
    if (!labelPrinter) {
      Swal.fire({
        position: "bottom-end",
        icon: "warning",
        text: t("Please select a label printer first"),
        showConfirmButton: false,
        timer: 1500
      });
      return;
    }

    const defaultTotalCartons = Math.max(1, doPickOrder.numberOfCartons || 1);
    const result = await Swal.fire({
      title: t("Reprint DN Label"),
      html: `
        <div style="display:flex;flex-direction:column;gap:10px;text-align:left;">
          <div style="display:flex;align-items:center;gap:12px;">
            <label for="swal-from-carton" style="min-width:120px;">${t("From carton")}</label>
            <input id="swal-from-carton" class="swal2-input" type="number" min="1" step="1" value="1" style="margin:0;flex:1;outline:none;box-shadow:none;border:1px solid #d9d9d9;" onfocus="this.style.outline='none';this.style.boxShadow='none';this.style.borderColor='#d9d9d9';" />
          </div>
          <div style="display:flex;align-items:center;gap:12px;">
            <label for="swal-to-carton" style="min-width:120px;">${t("To carton")}</label>
            <input id="swal-to-carton" class="swal2-input" type="number" min="1" step="1" value="1" style="margin:0;flex:1;outline:none;box-shadow:none;border:1px solid #d9d9d9;" onfocus="this.style.outline='none';this.style.boxShadow='none';this.style.borderColor='#d9d9d9';" />
          </div>
          <div style="display:flex;align-items:center;gap:12px;">
            <label for="swal-total-carton" style="min-width:120px;">${t("Total cartons on shipment")}</label>
            <input id="swal-total-carton" class="swal2-input" type="number" min="1" step="1" value="${defaultTotalCartons}" style="margin:0;flex:1;outline:none;box-shadow:none;border:1px solid #d9d9d9;" onfocus="this.style.outline='none';this.style.boxShadow='none';this.style.borderColor='#d9d9d9';" />
          </div>
        </div>
      `,
      showCancelButton: true,
      confirmButtonText: t("Confirm"),
      cancelButtonText: t("Cancel"),
      confirmButtonColor: "#8dba00",
      cancelButtonColor: "#F04438",
      focusConfirm: false,
      preConfirm: () => {
        const fromCarton = Number((document.getElementById("swal-from-carton") as HTMLInputElement | null)?.value || "0");
        const toCarton = Number((document.getElementById("swal-to-carton") as HTMLInputElement | null)?.value || "0");
        const totalCartonsOnShipment = Number((document.getElementById("swal-total-carton") as HTMLInputElement | null)?.value || "0");

        if (!Number.isInteger(fromCarton) || fromCarton < 1) {
          Swal.showValidationMessage(t("From carton must be at least 1"));
          return null;
        }
        if (!Number.isInteger(toCarton) || toCarton < fromCarton) {
          Swal.showValidationMessage(t("To carton must be greater than or equal to from carton"));
          return null;
        }
        if (!Number.isInteger(totalCartonsOnShipment) || totalCartonsOnShipment < 1) {
          Swal.showValidationMessage(t("Total cartons on shipment must be at least 1"));
          return null;
        }
        if (toCarton > totalCartonsOnShipment) {
          Swal.showValidationMessage(t("To carton cannot be greater than total cartons on shipment"));
          return null;
        }

        return {
          fromCarton,
          toCarton,
          totalCartonsOnShipment,
        };
      }
    });

    if (!result.isConfirmed || !result.value) {
      return;
    }

    try {
      const response = await printDNLabelsReprintWorkbench({
        deliveryOrderPickOrderId: doPickOrder.doPickOrderRecordId,
        printerId: labelPrinter.id,
        printQty: 1,
        fromCarton: result.value.fromCarton,
        toCarton: result.value.toCarton,
        totalCartonsOnShipment: result.value.totalCartonsOnShipment,
      });

      if (response.success) {
        Swal.fire({
          position: "bottom-end",
          icon: "success",
          text: t("Printed Successfully."),
          showConfirmButton: false,
          timer: 1500
        });
      } else {
        console.error("Reprint failed:", response.message);
      }
    } catch (error) {
      console.error("reprint error: ", error);
    }
  }, [labelPrinter, t]);

  const handleDetailClick = useCallback(
    async (record: CompletedDoPickOrderResponse) => {
      setSelectedRecord(record);
      setShowDetailView(true);
      try {
        const hierarchicalData = await fetchWorkbenchCompletedLotDetails(record.doPickOrderRecordId);
        const flatLotData: any[] = [];

        if (hierarchicalData?.pickOrders?.length > 0) {
          const toProc = (s?: string) => {
            if (!s) return "pending";
            const v = s.toLowerCase();
            if (v === "completed" || v === "complete") return "completed";
            if (v === "rejected") return "rejected";
            if (v === "partially_completed") return "pending";
            return "pending";
          };

          hierarchicalData.pickOrders.forEach((po: any) => {
            po.pickOrderLines?.forEach((line: any) => {
              const lineRequiredQty = Number(line.requiredQty ?? line.qty ?? 0);
              const lineStockouts = line.stockouts || [];
              const lots = line.lots || [];

              if (lots.length > 0) {
                lots.forEach((lot: any) => {
                  const sos = lineStockouts.filter((so: any) => (so.lotId ?? null) === (lot.id ?? null));
                  if (sos.length > 0) {
                    sos.forEach((so: any) => {
                      flatLotData.push({
                        pickOrderCode: po.pickOrderCodes?.[0] || po.pickOrderCode,
                        pickOrderLineId: line.id,
                        itemCode: line.item?.code,
                        itemName: line.item?.name,
                        lotNo: so.lotNo || lot.lotNo,
                        location: so.location || lot.location,
                        deliveryOrderCode: po.deliveryOrderCodes?.[0] || po.deliveryOrderCode,
                        pickOrderLineRequiredQty: lineRequiredQty,
                        requiredQty:
                          so?.requiredQty ?? so?.suggestedPickLotQty ?? lot?.requiredQty ?? null,
                        actualPickQty: so.qty ?? lot.actualPickQty ?? 0,
                        processingStatus: toProc(so.status),
                        stockOutLineStatus: so.status,
                        noLot: so.noLot === true,
                      });
                    });
                  } else {
                    flatLotData.push({
                      pickOrderCode: po.pickOrderCodes?.[0] || po.pickOrderCode,
                      pickOrderLineId: line.id,
                      itemCode: line.item?.code,
                      itemName: line.item?.name,
                      lotNo: lot.lotNo,
                      location: lot.location,
                      deliveryOrderCode: po.deliveryOrderCodes?.[0] || po.deliveryOrderCode,
                      pickOrderLineRequiredQty: lineRequiredQty,
                      requiredQty: lot.requiredQty ?? null,
                      actualPickQty: lot.actualPickQty ?? 0,
                      processingStatus: lot.processingStatus || "pending",
                      stockOutLineStatus: lot.stockOutLineStatus || "pending",
                      noLot: false,
                    });
                  }
                });
              } else if (lineStockouts.length > 0) {
                lineStockouts.forEach((so: any) => {
                  flatLotData.push({
                    pickOrderCode: po.pickOrderCodes?.[0] || po.pickOrderCode,
                    pickOrderLineId: line.id,
                    itemCode: line.item?.code,
                    itemName: line.item?.name,
                    lotNo: so.lotNo || "",
                    location: so.location || "",
                    deliveryOrderCode: po.deliveryOrderCodes?.[0] || po.deliveryOrderCode,
                    pickOrderLineRequiredQty: lineRequiredQty,
                    requiredQty: so?.requiredQty ?? so?.suggestedPickLotQty ?? null,
                    actualPickQty: so.qty ?? 0,
                    processingStatus: toProc(so.status),
                    stockOutLineStatus: so.status,
                    noLot: so.noLot === true,
                  });
                });
              }
            });
          });
        }
        setDetailLotData(flatLotData);
      } catch (e) {
        console.error("Failed to load completed lot details:", e);
        setDetailLotData([]);
      }
    },
    [],
  );

  const initialDetailOpenedRef = useRef(false);
  useEffect(() => {
    if (!openDetail) return;
    if (initialDetailOpenedRef.current || loading || !initialTicketNo?.trim()) return;
    const tn = initialTicketNo.trim();
    const match = records.find((r) => r.ticketNo?.trim() === tn);
    if (!match) return;
    initialDetailOpenedRef.current = true;
    void handleDetailClick(match);
  }, [openDetail, records, loading, initialTicketNo, handleDetailClick]);

  const handleBackToList = useCallback(() => {
    setShowDetailView(false);
    setSelectedRecord(null);
    setDetailLotData([]);
  }, []);

  if (showDetailView && selectedRecord) {
    return (
      <Box>
        <Box sx={{ mb: 2, display: "flex", alignItems: "center", gap: 2 }}>
          <Button variant="outlined" onClick={handleBackToList}>
            {t("Back to List")}
          </Button>
          <Typography variant="h6">
            {t("Pick Order Details")}: {selectedRecord.ticketNo}
          </Typography>
          {isWorkbenchExtraTicket(selectedRecord.releaseType, selectedRecord.ticketNo) && (
            <Chip label={t("Etra")} color="secondary" size="small" />
          )}
        </Box>

        <Paper sx={{ mb: 2, p: 2 }}>
          <Stack spacing={1}>
            <Typography variant="subtitle1">
              <strong>{t("Shop Name")}:</strong> {selectedRecord.shopName}
            </Typography>
            <Typography variant="subtitle1">
              <strong>{t("Store ID")}:</strong> {selectedRecord.storeId}
            </Typography>
            <Typography variant="subtitle1">
              <strong>{t("Ticket No.")}:</strong> {selectedRecord.ticketNo}
            </Typography>
            <Typography variant="subtitle1">
              <strong>{t("Handler")}:</strong>{" "}
              {selectedRecord.handlerName?.trim() ? selectedRecord.handlerName : "—"}
            </Typography>
            <Typography variant="subtitle1">
              <strong>{t("Truck Lance Code")}:</strong> {selectedRecord.truckLanceCode}
            </Typography>
            <Typography variant="subtitle1">
              <strong>{t("Completed Date")}:</strong>{" "}
              {selectedRecord.completedDate ? dayjs(selectedRecord.completedDate).format(OUTPUT_DATE_FORMAT) : "-"}
            </Typography>
          </Stack>
        </Paper>

        {detailLotData.length === 0 ? (
          <Box sx={{ p: 3, textAlign: "center" }}>
            <Typography variant="body2" color="text.secondary">
              {t("No lot details found for this order")}
            </Typography>
          </Box>
        ) : (
          <Stack spacing={2}>
            {Object.entries(
              detailLotData.reduce((acc: any, lot: any) => {
                const key = lot.pickOrderCode || "Unknown";
                if (!acc[key]) acc[key] = { lots: [], deliveryOrderCode: lot.deliveryOrderCode || "N/A" };
                acc[key].lots.push(lot);
                return acc;
              }, {}),
            ).map(([pickOrderCode, data]: [string, any]) => (
              <Accordion key={pickOrderCode} defaultExpanded>
                <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                  <Typography variant="subtitle1" fontWeight="bold">
                    {t("Pick Order")}: {pickOrderCode} ({data.lots.length} {t("items")}){" | "}
                    {t("Delivery Order")}: {data.deliveryOrderCode}
                  </Typography>
                </AccordionSummary>
                <AccordionDetails>
                  <TableContainer component={Paper}>
                    <Table size="small">
                      <TableHead>
                        <TableRow>
                          <TableCell>{t("Index")}</TableCell>
                          <TableCell>{t("Item Code")}</TableCell>
                          <TableCell>{t("Item Name")}</TableCell>
                          <TableCell>{t("Lot No")}</TableCell>
                          <TableCell>{t("Location")}</TableCell>
                          <TableCell align="right">{t("Required Qty")}</TableCell>
                          <TableCell align="right">{t("Actual Pick Qty")}</TableCell>
                          <TableCell align="center">{t("Status")}</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {(() => {
                          const seenGroupKeys = new Set<string>();
                          return data.lots.map((lot: any, index: number) => {
                            const groupKey =
                              lot.pickOrderLineId != null
                                ? `pol:${lot.pickOrderLineId}`
                                : `item:${lot.itemCode || ""}__do:${lot.deliveryOrderCode || ""}`;
                            const isGroupFirst = !seenGroupKeys.has(groupKey);
                            if (isGroupFirst) {
                              seenGroupKeys.add(groupKey);
                            }
                            const requiredQtyDisplay = isGroupFirst
                              ? lot.pickOrderLineRequiredQty ?? null
                              : null;
                            return (
                              <TableRow key={index}>
                                <TableCell>{index + 1}</TableCell>
                                <TableCell>{lot.itemCode || "N/A"}</TableCell>
                                <TableCell>{lot.itemName || "N/A"}</TableCell>
                                <TableCell>{lot.lotNo || "N/A"}</TableCell>
                                <TableCell>{lot.location || "N/A"}</TableCell>
                                <TableCell align="right">{requiredQtyDisplay}</TableCell>
                                <TableCell align="right">{lot.actualPickQty || 0}</TableCell>
                                <TableCell align="center">
                                  <Chip
                                    label={t(lot.processingStatus || "unknown")}
                                    color={lot.processingStatus === "completed" ? "success" : "default"}
                                    size="small"
                                  />
                                </TableCell>
                              </TableRow>
                            );
                          });
                        })()}
                      </TableBody>
                    </Table>
                  </TableContainer>
                </AccordionDetails>
              </Accordion>
            ))}
          </Stack>
        )}
      </Box>
    );
  }

  return (
    <Box>
      <Box sx={{ mb: 2 }}>
        <SearchBox
          key={`workbench-search-${listScope}-${initialTicketNo ?? ""}-${initialTargetDate ?? ""}`}
          criteria={searchCriteria}
          onSearch={handleSearch}
          onReset={handleSearchReset}
        />
      </Box>
      <Stack
        direction="row"
        justifyContent="space-between"
        alignItems="center"
        sx={{ mb: 2, gap: 2, flexWrap: "wrap" }}
      >
        <Typography variant="body2" color="text.secondary">
          {t("Search date")}: {searchDateDisplay} | {t("Completed DO pick orders: ")} {records.length}
        </Typography>
      </Stack>

      {loading ? (
        <Box sx={{ display: "flex", justifyContent: "center", p: 3 }}>
          <CircularProgress />
        </Box>
      ) : records.length === 0 ? (
        <Box sx={{ p: 3, textAlign: "center" }}>
          <Typography variant="body2" color="text.secondary">
            {t("No completed DO pick orders found")}
          </Typography>
        </Box>
      ) : (
        <Stack spacing={2}>
          {records.map((row) => (
            <Card key={row.id}>
              <CardContent>
                <Stack direction="row" justifyContent="space-between" alignItems="center">
                  <Box>
                  <Stack direction="row" alignItems="center" spacing={1} flexWrap="wrap">
                  <Typography variant="h6">{row.deliveryNoteCode || "-"}</Typography>
                  {isWorkbenchExtraTicket(row.releaseType, row.ticketNo) && (
                    <Chip
                      label={t("Etra")}
                      color="secondary"
                      size="small"
                      sx={{
                        "& .MuiChip-label": { fontSize: (theme) => theme.typography.h6.fontSize, fontWeight: 600 },
                        height: 30,
                      }}
                    />
                  )}
                  <Chip
                    label={t("completed")}
                    color="success"
                    size="small"
                    sx={{
                      "& .MuiChip-label": { fontSize: (theme) => theme.typography.h6.fontSize, fontWeight: 600 },
                      height: 30,
                    }}
                  />
                </Stack>
                    <Typography variant="body2" color="text.secondary">
                      {row.ticketNo || "-"}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {row.shopName}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {t("Completed")}:{" "}
                      {row.completedDate ? dayjs(row.completedDate).format(OUTPUT_DATE_FORMAT) : "-"}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {t("Ticket No.")}: {row.ticketNo || "-"}
                    </Typography>
                  </Box>
                  {/*<Chip label={t("completed")} color="success" size="small" />*/}
                </Stack>
              </CardContent>
              <CardActions>
                <Button variant="outlined" onClick={() => void handleDetailClick(row)}>
                  {t("View Details")}
                </Button>
                <Button variant="contained" onClick={() => void handlePrintDN(row.doPickOrderRecordId)}>
                  {t("Print Pick Order")}
                </Button>
                <Button variant="contained" onClick={() => void handlePrintBoth(row.doPickOrderRecordId)}>
                  {t("Print DN & Label")}
                </Button>
                <Button variant="contained" onClick={() => void handlePrintLabel(row.doPickOrderRecordId)}>
                  {t("Print Label")}
                </Button>
                <Button variant="contained" onClick={() => void handleLabelReprint(row)}>
                  {t("Reprint Label(s)")}
                </Button>
              </CardActions>
            </Card>
          ))}
        </Stack>
      )}
    </Box>
  );
};

export default GoodPickExecutionWorkbenchRecord;
