"use client";

import { useEffect, useMemo, useState, useCallback } from "react";
import {
  fetchBags,
  fetchBagLotLines,
  fetchBagConsumptions,
  BagSummaryResponse,
  BagLotLineResponse,
  BagConsumptionResponse,
} from "@/app/api/bag/action";
import SearchResults, {
  Column,
  defaultPagingController,
} from "../SearchResults/SearchResults";
import { useTranslation } from "react-i18next";
import {
  integerFormatter,
  arrayToDateString,
  arrayToDateTimeString,
} from "@/app/utils/formatUtil";
import {
  Box,
  Typography,
  Stack,
  IconButton,
  Button,
} from "@mui/material";
import VisibilityIcon from "@mui/icons-material/Visibility";

type ViewLevel = "bag" | "lot" | "consumption";

const BagSearch: React.FC = () => {
  const { t } = useTranslation("jo");

  const [level, setLevel] = useState<ViewLevel>("bag");


  const [selectedBag, setSelectedBag] = useState<BagSummaryResponse | null>(null);
  const [selectedLotLine, setSelectedLotLine] = useState<BagLotLineResponse | null>(null);


  const [bags, setBags] = useState<BagSummaryResponse[]>([]);
  const [lotLines, setLotLines] = useState<BagLotLineResponse[]>([]);
  const [consumptions, setConsumptions] = useState<BagConsumptionResponse[]>([]);
  
  const [pagingController, setPagingController] = useState(defaultPagingController);
  const [totalCount, setTotalCount] = useState(0);

  const bagColumns = useMemo<Column<BagSummaryResponse>[]>(() => [
    {
      name: "bagName",
      label: t("Bag Name"),
      flex: 2,
    },
    {
      name: "bagCode",
      label: t("Bag Code"),
      flex: 1,
    },
    {
      name: "takenBagBalance",
      label: t("Balance"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.takenBagBalance ?? 0),
    },
    {
      name: "actions" as any,
      label: t("Actions"),
      align: "center",
      headerAlign: "center",
      renderCell: (row) => (
        <IconButton
          size="small"
          color="primary"
          onClick={() => handleViewBagDetail(row)}
        >
          <VisibilityIcon fontSize="small" />
        </IconButton>
      ),
    },
  ], [t]);


  const lotColumns = useMemo<Column<BagLotLineResponse>[]>(() => [
    {
      name: "lotNo",
      label: t("Lot No"),
      flex: 2,
    },
    {
      name: "startQty",
      label: t("Start Qty"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.startQty ?? 0),
    },
    {
      name: "consumedQty",
      label: t("Consumed Qty"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.consumedQty ?? 0),
    },
    {
      name: "scrapQty",
      label: t("Scrap Qty"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.scrapQty ?? 0),
    },
    {
      name: "balanceQty",
      label: t("Balance Qty"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.balanceQty ?? 0),
    },
    {
      name: "actions" as any,
      label: t("Actions"),
      align: "center",
      headerAlign: "center",
      renderCell: (row) => (
        <IconButton
          size="small"
          color="primary"
          onClick={() => handleViewLotDetail(row)}
        >
          <VisibilityIcon fontSize="small" />
        </IconButton>
      ),
    },
  ], [t]);


  const consColumns = useMemo<Column<BagConsumptionResponse>[]>(() => [
    {
      name: "jobOrderCode",
      label: t("Job Order Code"),
      flex: 2,
    },
    {
      name: "startQty",
      label: t("Start Qty"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.startQty ?? 0),
    },
    {
      name: "consumedQty",
      label: t("Consumed Qty"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.consumedQty ?? 0),
    },
    {
      name: "scrapQty",
      label: t("Scrap Qty"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.scrapQty ?? 0),
    },
    {
      name: "endQty",
      label: t("End Qty"),
      align: "right",
      headerAlign: "right",
      renderCell: (row) => integerFormatter.format(row.endQty ?? 0),
    },
    {
      name: "date",
      label: t("Date"),
      renderCell: (row) =>
        row.date ? arrayToDateString(row.date as any) : "-",
    },
    {
      name: "time",
      label: t("Time"),
      renderCell: (row) =>
        row.time ? arrayToDateTimeString(row.time as any) : "-",
    },
  ], [t]);


  useEffect(() => {
    const load = async () => {
      const data = await fetchBags();
      const safe = data ?? [];
      setBags(safe);
      setTotalCount(safe.length);
      setPagingController(defaultPagingController);
      setLevel("bag");
      setSelectedBag(null);
      setSelectedLotLine(null);
      setLotLines([]);
      setConsumptions([]);
    };
    load();
  }, []);

  const handleViewBagDetail = useCallback(async (row: BagSummaryResponse) => {
    setSelectedBag(row);
    setLevel("lot");
    setPagingController(defaultPagingController);
    setSelectedLotLine(null);
    setConsumptions([]);
    const data = await fetchBagLotLines(row.id);
    const safe = data ?? [];
    setLotLines(safe);
    setTotalCount(safe.length);
  }, []);


  const handleViewLotDetail = useCallback(async (row: BagLotLineResponse) => {
    setSelectedLotLine(row);
    setLevel("consumption");
    setPagingController(defaultPagingController);
    const data = await fetchBagConsumptions(row.id);
    const safe = data ?? [];
    setConsumptions(safe);
    setTotalCount(safe.length);
  }, []);


  const handleBack = useCallback(async () => {
    if (level === "consumption" && selectedBag) {

      setLevel("lot");
      setSelectedLotLine(null);
      setPagingController(defaultPagingController);
      const data = await fetchBagLotLines(selectedBag.id);
      const safe = data ?? [];
      setLotLines(safe);
      setTotalCount(safe.length);
      return;
    }
    if (level === "lot") {

      setLevel("bag");
      setSelectedBag(null);
      setSelectedLotLine(null);
      setPagingController(defaultPagingController);
      setTotalCount(bags.length);
      return;
    }
  }, [level, selectedBag, bags]);


  const { title, items, columns } = useMemo(() => {
    if (level === "bag") {
      return {
        title: t("Bag List"),
        items: bags,
        columns: bagColumns,
      };
    }
    if (level === "lot") {
      return {
        title: `${t("Bag Lot Lines")}${
          selectedBag ? ` - ${selectedBag.bagName ?? ""} (${selectedBag.bagCode ?? ""})` : ""
        }`,
        items: lotLines,
        columns: lotColumns,
      };
    }
    
    return {
      title: `${t("Bag Consumption Records")}${
        selectedLotLine ? ` - ${selectedLotLine.lotNo ?? ""}` : ""
      }`,
      items: consumptions,
      columns: consColumns,
    };
  }, [level, t, bags, bagColumns, lotLines, lotColumns, consumptions, consColumns, selectedBag, selectedLotLine]);



  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
      <Stack direction="row" justifyContent="space-between" alignItems="center">
        <Typography variant="h5">
          {t(" ")}
        </Typography>

        <Stack direction="row" spacing={1}>
          {level !== "bag" && (
            <Button variant="outlined" onClick={handleBack}>
              {t("Back")}
            </Button>
          )}
        </Stack>
      </Stack>

      <Typography variant="h6" gutterBottom>
        {title}
      </Typography>

      <SearchResults<any>
        items={items ?? []}
        columns={columns as any}
        setPagingController={setPagingController}
        pagingController={pagingController}
        totalCount={totalCount}
        isAutoPaging={false}
      />
    </Box>
  );
};

export default BagSearch;