"use client";

import { Box, Tab, Tabs, Snackbar, Alert, CircularProgress, Typography } from "@mui/material";
import { useState, useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { AllPickedStockTakeListReponse, getApproverStockTakeRecords } from "@/app/api/stockTake/actions";
import PickerCardList from "./PickerCardList";
import PickerStockTake from "./PickerStockTake";
import PickerReStockTake from "./PickerReStockTake";
import ApproverStockTakeAll from "./ApproverStockTakeAll";

type ViewScope = "picker" | "approver-all";

const StockTakeTab: React.FC = () => {
  const { t } = useTranslation(["inventory", "common"]);
  const [tabValue, setTabValue] = useState(0);
  const [selectedSession, setSelectedSession] = useState<AllPickedStockTakeListReponse | null>(null);
  const [viewMode, setViewMode] = useState<"details" | "reStockTake">("details");
  const [viewScope, setViewScope] = useState<ViewScope>("picker");
  const [approverSession, setApproverSession] = useState<AllPickedStockTakeListReponse | null>(null);
  const [approverLoading, setApproverLoading] = useState(false);
  const [snackbar, setSnackbar] = useState<{ 
    open: boolean; 
    message: string; 
    severity: "success" | "error" | "warning" 
  }>({
    open: false,
    message: "",
    severity: "success",
  });

  const handleCardClick = useCallback((session: AllPickedStockTakeListReponse) => {
    setSelectedSession(session);
    setViewMode("details");
  }, []);

  const handleReStockTakeClick = useCallback((session: AllPickedStockTakeListReponse) => {
    setSelectedSession(session);
    setViewMode("reStockTake");
    setViewScope("picker");
  }, []);

  const handleBackToList = useCallback(() => {
    setSelectedSession(null);
    setViewMode("details");
  }, []);

  const handleSnackbar = useCallback((message: string, severity: "success" | "error" | "warning") => {
    setSnackbar({
      open: true,
      message,
      severity,
    });
  }, []);

  useEffect(() => {
    if (tabValue !== 1) return;
    setApproverLoading(true);
    getApproverStockTakeRecords()
      .then((records) => {
        const list = Array.isArray(records) ? records : [];
        setApproverSession(list[0] ?? null);
      })
      .catch((e) => {
        console.error(e);
        setApproverSession(null);
      })
      .finally(() => setApproverLoading(false));
  }, [tabValue]);

  if (selectedSession && viewScope === "picker") {
    return (
      <Box>
        {viewScope === "picker" && (
          tabValue === 0 ? (
            viewMode === "reStockTake" ? (
              <PickerReStockTake
                selectedSession={selectedSession}
                onBack={handleBackToList}
                onSnackbar={handleSnackbar}
              />
            ) : (
              <PickerStockTake
                selectedSession={selectedSession}
                onBack={handleBackToList}
                onSnackbar={handleSnackbar}
              />
            )
          ) : null
        )}
        <Snackbar
          open={snackbar.open}
          autoHideDuration={6000}
          onClose={() => setSnackbar({ ...snackbar, open: false })}
        >
          <Alert onClose={() => setSnackbar({ ...snackbar, open: false })} severity={snackbar.severity}>
            {snackbar.message}
          </Alert>
        </Snackbar>
      </Box>
    );
  }

  return (
    <Box>
      <Tabs
        value={tabValue}
        onChange={(e, newValue) => {
          setTabValue(newValue);
          if (newValue === 0) {
            setViewScope("picker");
          } else {
            setViewScope("approver-all");
          }
        }}
        sx={{ mb: 2 }}
      >
        <Tab label={t("Picker")} />
        <Tab label={t("Approver Pending")} />
        <Tab label={t("Approver Approved")} />
      </Tabs>

      {tabValue === 0 && (
        <PickerCardList 
          onCardClick={(session) => {
            setViewScope("picker");
            handleCardClick(session);
          }}
          onReStockTakeClick={handleReStockTakeClick}
        />
      )}
      {tabValue === 1 && (
        <Box>
          {approverLoading ? (
            <Box sx={{ display: "flex", justifyContent: "center", p: 3 }}>
              <CircularProgress />
            </Box>
          ) : approverSession ? (
            <ApproverStockTakeAll
              selectedSession={approverSession}
              mode="pending"
              onSnackbar={handleSnackbar}
            />
          ) : (
            <Typography variant="body2" color="text.secondary">
              {t("No data")}
            </Typography>
          )}
        </Box>
      )}
      {tabValue === 2 && (
        <Box>
          {approverLoading ? (
            <Box sx={{ display: "flex", justifyContent: "center", p: 3 }}>
              <CircularProgress />
            </Box>
          ) : approverSession ? (
            <ApproverStockTakeAll
              selectedSession={approverSession}
              mode="approved"
              onSnackbar={handleSnackbar}
            />
          ) : (
            <Typography variant="body2" color="text.secondary">
              {t("No data")}
            </Typography>
          )}
        </Box>
      )}

      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert onClose={() => setSnackbar({ ...snackbar, open: false })} severity={snackbar.severity}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default StockTakeTab;