"use client";

import {
  Box,
  Button,
  Card,
  CardContent,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Typography,
  Paper,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from "@mui/material";
import { useState, useMemo, useCallback } from "react";
import { useTranslation } from "react-i18next";
import SearchBox, { Criterion } from "../SearchBox";
import SearchResults, { Column } from "../SearchResults";
import { defaultPagingController } from "../SearchResults/SearchResults";

// Fake data types
interface Floor {
  id: number;
  code: string;
  name: string;
  warehouseCode: string;
  warehouseName: string;
}

interface Zone {
  id: number;
  floorId: number;
  code: string;
  name: string;
  description: string;
}

interface InventoryLotLineForStockTake {
  id: number;
  zoneId: number;
  itemCode: string;
  itemName: string;
  lotNo: string;
  location: string;
  systemQty: number;
  countedQty?: number;
  variance?: number;
  uom: string;
}

// Fake data
const fakeFloors: Floor[] = [
  { id: 1, code: "F1", name: "1st Floor", warehouseCode: "WH001", warehouseName: "Main Warehouse" },
  { id: 2, code: "F2", name: "2nd Floor", warehouseCode: "WH001", warehouseName: "Main Warehouse" },
  { id: 3, code: "F3", name: "3rd Floor", warehouseCode: "WH001", warehouseName: "Main Warehouse" },
];

const fakeZones: Zone[] = [
  { id: 1, floorId: 1, code: "Z-A", name: "Zone A", description: "Row 1-5" },
  { id: 2, floorId: 1, code: "Z-B", name: "Zone B", description: "Row 6-10" },
  { id: 3, floorId: 2, code: "Z-C", name: "Zone C", description: "Row 1-5" },
  { id: 4, floorId: 2, code: "Z-D", name: "Zone D", description: "Row 6-10" },
  { id: 5, floorId: 3, code: "Z-E", name: "Zone E", description: "Row 1-5" },
];

const fakeLots: InventoryLotLineForStockTake[] = [
  { id: 1, zoneId: 1, itemCode: "M001", itemName: "Material A", lotNo: "LOT-2024-001", location: "A-01-01", systemQty: 100, uom: "PCS" },
  { id: 2, zoneId: 1, itemCode: "M002", itemName: "Material B", lotNo: "LOT-2024-002", location: "A-01-02", systemQty: 50, uom: "PCS" },
  { id: 3, zoneId: 1, itemCode: "M003", itemName: "Material C", lotNo: "LOT-2024-003", location: "A-01-03", systemQty: 75, uom: "KG" },
  { id: 4, zoneId: 2, itemCode: "M004", itemName: "Material D", lotNo: "LOT-2024-004", location: "B-01-01", systemQty: 200, uom: "PCS" },
  { id: 5, zoneId: 2, itemCode: "M005", itemName: "Material E", lotNo: "LOT-2024-005", location: "B-01-02", systemQty: 150, uom: "KG" },
];

type FloorSearchQuery = {
  floorCode: string;
  floorName: string;
  warehouseCode: string;
};

type FloorSearchParamNames = keyof FloorSearchQuery;

const StockTakeTab: React.FC = () => {
  const { t } = useTranslation(["inventory"]);

  // Search states for floors
  const defaultFloorInputs = useMemo(() => ({
    floorCode: "",
    floorName: "",
    warehouseCode: "",
  }), []);
  const [floorInputs, setFloorInputs] = useState<Record<FloorSearchParamNames, string>>(defaultFloorInputs);

  // Selection states
  const [selectedFloor, setSelectedFloor] = useState<Floor | null>(null);
  const [selectedZone, setSelectedZone] = useState<Zone | null>(null);

  // Paging controllers
  const [floorsPagingController, setFloorsPagingController] = useState(defaultPagingController);
  const [zonesPagingController, setZonesPagingController] = useState(defaultPagingController);
  const [lotsPagingController, setLotsPagingController] = useState(defaultPagingController);

  // Stock take dialog
  const [stockTakeDialogOpen, setStockTakeDialogOpen] = useState(false);
  const [selectedLot, setSelectedLot] = useState<InventoryLotLineForStockTake | null>(null);
  const [countedQty, setCountedQty] = useState<number>(0);
  const [remark, setRemark] = useState("");

  // Filtered data
  const filteredFloors = useMemo(() => {
    return fakeFloors.filter(floor => {
      if (floorInputs.floorCode && !floor.code.toLowerCase().includes(floorInputs.floorCode.toLowerCase())) {
        return false;
      }
      if (floorInputs.floorName && !floor.name.toLowerCase().includes(floorInputs.floorName.toLowerCase())) {
        return false;
      }
      if (floorInputs.warehouseCode && !floor.warehouseCode.toLowerCase().includes(floorInputs.warehouseCode.toLowerCase())) {
        return false;
      }
      return true;
    });
  }, [floorInputs]);

  const filteredZones = useMemo(() => {
    if (!selectedFloor) return [];
    return fakeZones.filter(zone => zone.floorId === selectedFloor.id);
  }, [selectedFloor]);

  const filteredLots = useMemo(() => {
    if (!selectedZone) return [];
    return fakeLots.filter(lot => lot.zoneId === selectedZone.id);
  }, [selectedZone]);

  // Search criteria
  const floorSearchCriteria: Criterion<FloorSearchParamNames>[] = useMemo(
    () => [
      { label: t("Floor Code"), paramName: "floorCode", type: "text" },
      { label: t("Floor Name"), paramName: "floorName", type: "text" },
      { label: t("Warehouse Code"), paramName: "warehouseCode", type: "text" },
    ],
    [t],
  );

  // Handlers
  const handleFloorSearch = useCallback((query: Record<FloorSearchParamNames, string>) => {
    setFloorInputs(() => query);
    setFloorsPagingController(() => defaultPagingController);
  }, []);

  const handleFloorReset = useCallback(() => {
    setFloorInputs(() => defaultFloorInputs);
    setFloorsPagingController(() => defaultPagingController);
    setSelectedFloor(null);
    setSelectedZone(null);
  }, [defaultFloorInputs]);

  const handleFloorClick = useCallback((floor: Floor) => {
    setSelectedFloor(floor);
    setSelectedZone(null);
    setZonesPagingController(() => defaultPagingController);
    setLotsPagingController(() => defaultPagingController);
  }, []);

  const handleZoneClick = useCallback((zone: Zone) => {
    setSelectedZone(zone);
    setLotsPagingController(() => defaultPagingController);
  }, []);

  const handleStockTakeClick = useCallback((lot: InventoryLotLineForStockTake) => {
    setSelectedLot(lot);
    setCountedQty(lot.countedQty || lot.systemQty);
    setRemark("");
    setStockTakeDialogOpen(true);
  }, []);

  const handleStockTakeSubmit = useCallback(() => {
    if (!selectedLot) return;

    const variance = countedQty - selectedLot.systemQty;
    
    // Here you would call the API to submit stock take
    console.log("Stock Take Submitted:", {
      lotId: selectedLot.id,
      systemQty: selectedLot.systemQty,
      countedQty: countedQty,
      variance: variance,
      remark: remark,
    });

    alert(`${t("Stock take recorded successfully!")}\n${t("Variance")}: ${variance > 0 ? '+' : ''}${variance}`);
    
    // Update the lot with counted qty (in real app, this would come from backend)
    selectedLot.countedQty = countedQty;
    selectedLot.variance = variance;

    setStockTakeDialogOpen(false);
    setSelectedLot(null);
  }, [selectedLot, countedQty, remark, t]);

  const handleDialogClose = useCallback(() => {
    setStockTakeDialogOpen(false);
    setSelectedLot(null);
  }, []);

  // Floor columns
  const floorColumns: Column<Floor>[] = useMemo(
    () => [
      { name: "code", label: t("Floor Code") },
      { name: "name", label: t("Floor Name") },
      {
        name: "warehouseCode",
        label: t("Warehouse"),
        renderCell: (params) => `${params.warehouseCode} - ${params.warehouseName}`,
      },
    ],
    [t],
  );

  // Zone columns
  const zoneColumns: Column<Zone>[] = useMemo(
    () => [
      { name: "code", label: t("Zone Code") },
      { name: "name", label: t("Zone Name") },
      { name: "description", label: t("Description") },
    ],
    [t],
  );

  // Lot columns
  const lotColumns: Column<InventoryLotLineForStockTake>[] = useMemo(
    () => [
      { name: "itemCode", label: t("Item Code") },
      { name: "itemName", label: t("Item Name") },
      { name: "lotNo", label: t("Lot No") },
      { name: "location", label: t("Location") },
      { name: "systemQty", label: t("System Qty"), align: "right", type: "integer" },
      {
        name: "countedQty",
        label: t("Counted Qty"),
        align: "right",
        renderCell: (params) => params.countedQty || "-",
      },
      {
        name: "variance",
        label: t("Variance"),
        align: "right",
        renderCell: (params) => {
          if (params.variance === undefined) return "-";
          const variance = params.variance;
          return (
            <Typography
              variant="body2"
              sx={{
                color: variance === 0 ? "inherit" : variance > 0 ? "success.main" : "error.main",
                fontWeight: variance !== 0 ? "bold" : "normal",
              }}
            >
              {variance > 0 ? `+${variance}` : variance}
            </Typography>
          );
        },
      },
      { name: "uom", label: t("UOM") },
      {
        name: "id",
        label: t("Action"),
        renderCell: (params) => (
          <Button size="small" variant="outlined" onClick={() => handleStockTakeClick(params)}>
            {t("Stock Take")}
          </Button>
        ),
      },
    ],
    [t, handleStockTakeClick],
  );

  return (
    <Box>
      <Alert severity="info" sx={{ mb: 3 }}>
        {t("This is a demo with fake data. API integration pending.")}
      </Alert>

      {/* Step 1: Select Floor */}
      <Typography variant="h6" sx={{ mb: 2 }}>
        {t("Step 1: Select Floor")}
      </Typography>
      <SearchBox
        criteria={floorSearchCriteria}
        onSearch={handleFloorSearch}
        onReset={handleFloorReset}
      />
      <SearchResults<Floor>
        items={filteredFloors}
        columns={floorColumns}
        pagingController={floorsPagingController}
        setPagingController={setFloorsPagingController}
        totalCount={filteredFloors.length}
        onRowClick={handleFloorClick}
      />

      {/* Step 2: Select Zone */}
      {selectedFloor && (
        <>
          <Typography variant="h6" sx={{ mt: 4, mb: 2 }}>
            {t("Step 2: Select Zone")} - {selectedFloor.name}
          </Typography>
          <SearchResults<Zone>
            items={filteredZones}
            columns={zoneColumns}
            pagingController={zonesPagingController}
            setPagingController={setZonesPagingController}
            totalCount={filteredZones.length}
            onRowClick={handleZoneClick}
          />
        </>
      )}

      {/* Step 3: Stock Take */}
      {selectedZone && (
        <>
          <Typography variant="h6" sx={{ mt: 4, mb: 2 }}>
            {t("Step 3: Perform Stock Take")} - {selectedZone.name}
          </Typography>
          <SearchResults<InventoryLotLineForStockTake>
            items={filteredLots}
            columns={lotColumns}
            pagingController={lotsPagingController}
            setPagingController={setLotsPagingController}
            totalCount={filteredLots.length}
          />
        </>
      )}

      {/* Stock Take Dialog */}
      <Dialog open={stockTakeDialogOpen} onClose={handleDialogClose} maxWidth="sm" fullWidth>
        <DialogTitle>{t("Stock Take")}</DialogTitle>
        <DialogContent>
          {selectedLot && (
            <Stack spacing={3} sx={{ mt: 2 }}>
              <Box>
                <Typography variant="subtitle2" color="text.secondary">
                  {t("Item")}
                </Typography>
                <Typography variant="body1">
                  {selectedLot.itemCode} - {selectedLot.itemName}
                </Typography>
              </Box>

              <Box>
                <Typography variant="subtitle2" color="text.secondary">
                  {t("Lot No")}
                </Typography>
                <Typography variant="body1">{selectedLot.lotNo}</Typography>
              </Box>

              <Box>
                <Typography variant="subtitle2" color="text.secondary">
                  {t("Location")}
                </Typography>
                <Typography variant="body1">{selectedLot.location}</Typography>
              </Box>

              <Box>
                <Typography variant="subtitle2" color="text.secondary">
                  {t("System Qty")}
                </Typography>
                <Typography variant="body1">
                  {selectedLot.systemQty} {selectedLot.uom}
                </Typography>
              </Box>

              <TextField
                label={t("Counted Qty")}
                type="number"
                value={countedQty}
                onChange={(e) => setCountedQty(parseInt(e.target.value) || 0)}
                fullWidth
                autoFocus
              />

              <Box>
                <Typography variant="subtitle2" color="text.secondary">
                  {t("Variance")}
                </Typography>
                <Typography
                  variant="h6"
                  sx={{
                    color:
                      countedQty - selectedLot.systemQty === 0
                        ? "inherit"
                        : countedQty - selectedLot.systemQty > 0
                        ? "success.main"
                        : "error.main",
                  }}
                >
                  {countedQty - selectedLot.systemQty > 0 ? "+" : ""}
                  {countedQty - selectedLot.systemQty}
                </Typography>
              </Box>

              <TextField
                label={t("Remark")}
                multiline
                rows={3}
                value={remark}
                onChange={(e) => setRemark(e.target.value)}
                fullWidth
              />
            </Stack>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDialogClose}>{t("Cancel")}</Button>
          <Button onClick={handleStockTakeSubmit} variant="contained" color="primary">
            {t("Submit Stock Take")}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default StockTakeTab;