"use client";

import {
  Box,
  Card,
  CardContent,
  Chip,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  TextField,
  Typography,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
} from "@mui/material";
import { useState, useMemo } from "react";
import { useTranslation } from "react-i18next";
import dayjs from "dayjs";
import { OUTPUT_DATE_FORMAT } from "@/app/utils/formatUtil";

// Fake data types
interface InventoryAdjustment {
  id: number;
  adjustmentNo: string;
  type: "stock_take" | "manual" | "damage" | "return";
  itemCode: string;
  itemName: string;
  lotNo: string;
  location: string;
  beforeQty: number;
  afterQty: number;
  adjustmentQty: number;
  reason: string;
  adjustedBy: string;
  adjustedDate: string;
  status: "approved" | "pending" | "rejected";
}

// Fake data
const fakeAdjustments: InventoryAdjustment[] = [
  {
    id: 1,
    adjustmentNo: "ADJ-2024-001",
    type: "stock_take",
    itemCode: "M001",
    itemName: "Material A",
    lotNo: "LOT-2024-001",
    location: "A-01-01",
    beforeQty: 100,
    afterQty: 98,
    adjustmentQty: -2,
    reason: "Stock take variance",
    adjustedBy: "John Doe",
    adjustedDate: "2024-10-10T10:30:00",
    status: "approved",
  },
  {
    id: 2,
    adjustmentNo: "ADJ-2024-002",
    type: "damage",
    itemCode: "M003",
    itemName: "Material C",
    lotNo: "LOT-2024-003",
    location: "A-01-03",
    beforeQty: 75,
    afterQty: 70,
    adjustmentQty: -5,
    reason: "Damaged during handling",
    adjustedBy: "Jane Smith",
    adjustedDate: "2024-10-11T14:20:00",
    status: "approved",
  },
  {
    id: 3,
    adjustmentNo: "ADJ-2024-003",
    type: "manual",
    itemCode: "M002",
    itemName: "Material B",
    lotNo: "LOT-2024-002",
    location: "A-01-02",
    beforeQty: 50,
    afterQty: 55,
    adjustmentQty: 5,
    reason: "Found extra stock",
    adjustedBy: "John Doe",
    adjustedDate: "2024-10-12T09:15:00",
    status: "pending",
  },
  {
    id: 4,
    adjustmentNo: "ADJ-2024-004",
    type: "return",
    itemCode: "M001",
    itemName: "Material A",
    lotNo: "LOT-2024-004",
    location: "A-02-01",
    beforeQty: 30,
    afterQty: 35,
    adjustmentQty: 5,
    reason: "Return from production",
    adjustedBy: "Mike Johnson",
    adjustedDate: "2024-10-13T11:45:00",
    status: "approved",
  },
];

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

  // States
  const [adjustments] = useState<InventoryAdjustment[]>(fakeAdjustments);
  const [typeFilter, setTypeFilter] = useState<string>("all");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [searchText, setSearchText] = useState("");

  // Pagination
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);

  // Filter adjustments
  const filteredAdjustments = useMemo(() => {
    return adjustments.filter((adj) => {
      // Type filter
      if (typeFilter !== "all" && adj.type !== typeFilter) {
        return false;
      }

      // Status filter
      if (statusFilter !== "all" && adj.status !== statusFilter) {
        return false;
      }

      // Search filter
      if (searchText) {
        const search = searchText.toLowerCase();
        return (
          adj.adjustmentNo.toLowerCase().includes(search) ||
          adj.itemCode.toLowerCase().includes(search) ||
          adj.itemName.toLowerCase().includes(search) ||
          adj.lotNo.toLowerCase().includes(search)
        );
      }

      return true;
    });
  }, [adjustments, typeFilter, statusFilter, searchText]);

  // Pagination
  const paginatedAdjustments = useMemo(() => {
    const startIndex = page * rowsPerPage;
    return filteredAdjustments.slice(startIndex, startIndex + rowsPerPage);
  }, [filteredAdjustments, page, rowsPerPage]);

  const handlePageChange = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const getAdjustmentTypeColor = (type: string) => {
    switch (type) {
      case "stock_take":
        return "primary";
      case "manual":
        return "info";
      case "damage":
        return "error";
      case "return":
        return "success";
      default:
        return "default";
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "approved":
        return "success";
      case "pending":
        return "warning";
      case "rejected":
        return "error";
      default:
        return "default";
    }
  };

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

      {/* Filters */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Stack direction="row" spacing={2} alignItems="center">
            <FormControl sx={{ minWidth: 150 }}>
              <InputLabel>{t("Type")}</InputLabel>
              <Select
                value={typeFilter}
                label={t("Type")}
                onChange={(e) => setTypeFilter(e.target.value)}
              >
                <MenuItem value="all">{t("All")}</MenuItem>
                <MenuItem value="stock_take">{t("Stock Take")}</MenuItem>
                <MenuItem value="manual">{t("Manual")}</MenuItem>
                <MenuItem value="damage">{t("Damage")}</MenuItem>
                <MenuItem value="return">{t("Return")}</MenuItem>
              </Select>
            </FormControl>

            <FormControl sx={{ minWidth: 150 }}>
              <InputLabel>{t("Status")}</InputLabel>
              <Select
                value={statusFilter}
                label={t("Status")}
                onChange={(e) => setStatusFilter(e.target.value)}
              >
                <MenuItem value="all">{t("All")}</MenuItem>
                <MenuItem value="approved">{t("Approved")}</MenuItem>
                <MenuItem value="pending">{t("Pending")}</MenuItem>
                <MenuItem value="rejected">{t("Rejected")}</MenuItem>
              </Select>
            </FormControl>

            <TextField
              label={t("Search")}
              variant="outlined"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              placeholder={t("Adjustment No, Item, Lot...")}
              sx={{ flexGrow: 1 }}
            />
          </Stack>

          <Typography variant="body2" color="text.secondary" sx={{ mt: 2 }}>
            {t("Total Adjustments")}: {filteredAdjustments.length}
          </Typography>
        </CardContent>
      </Card>

      {/* Table */}
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>{t("Adjustment No")}</TableCell>
              <TableCell>{t("Type")}</TableCell>
              <TableCell>{t("Item")}</TableCell>
              <TableCell>{t("Lot No")}</TableCell>
              <TableCell>{t("Location")}</TableCell>
              <TableCell align="right">{t("Before Qty")}</TableCell>
              <TableCell align="right">{t("After Qty")}</TableCell>
              <TableCell align="right">{t("Adjustment")}</TableCell>
              <TableCell>{t("Reason")}</TableCell>
              <TableCell>{t("Adjusted By")}</TableCell>
              <TableCell>{t("Date")}</TableCell>
              <TableCell>{t("Status")}</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {paginatedAdjustments.length === 0 ? (
              <TableRow>
                <TableCell colSpan={12} align="center">
                  <Typography variant="body2" color="text.secondary" sx={{ py: 3 }}>
                    {t("No adjustments found")}
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              paginatedAdjustments.map((adj) => (
                <TableRow key={adj.id} hover>
                  <TableCell>{adj.adjustmentNo}</TableCell>
                  <TableCell>
                    <Chip
                      label={t(adj.type)}
                      size="small"
                      color={getAdjustmentTypeColor(adj.type)}
                    />
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">{adj.itemCode}</Typography>
                    <Typography variant="caption" color="text.secondary">
                      {adj.itemName}
                    </Typography>
                  </TableCell>
                  <TableCell>{adj.lotNo}</TableCell>
                  <TableCell>{adj.location}</TableCell>
                  <TableCell align="right">{adj.beforeQty}</TableCell>
                  <TableCell align="right">{adj.afterQty}</TableCell>
                  <TableCell
                    align="right"
                    sx={{
                      color: adj.adjustmentQty >= 0 ? "success.main" : "error.main",
                      fontWeight: "bold",
                    }}
                  >
                    {adj.adjustmentQty > 0 ? `+${adj.adjustmentQty}` : adj.adjustmentQty}
                  </TableCell>
                  <TableCell>{adj.reason}</TableCell>
                  <TableCell>{adj.adjustedBy}</TableCell>
                  <TableCell>{dayjs(adj.adjustedDate).format(OUTPUT_DATE_FORMAT)}</TableCell>
                  <TableCell>
                    <Chip label={t(adj.status)} size="small" color={getStatusColor(adj.status)} />
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <TablePagination
        component="div"
        count={filteredAdjustments.length}
        page={page}
        rowsPerPage={rowsPerPage}
        onPageChange={handlePageChange}
        onRowsPerPageChange={handleRowsPerPageChange}
        rowsPerPageOptions={[5, 10, 25, 50]}
      />
    </Box>
  );
};

export default InventoryAdjustmentsTab;