import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Box,
  Typography,
  Button,
  Paper,
  Grid,
  Chip,
  Card,
  CardContent,
  Alert,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
} from "@mui/material";
import {
  DataGrid,
  GridColDef,
  GridRenderCellParams,
  GridToolbar,
  GridRowModel,
} from "@mui/x-data-grid";
import {
  PlayArrow as StartIcon,
  CheckCircle as CompleteIcon,
  DoneAll as ConfirmIcon,
  ArrowBack as ArrowBackIcon,
} from "@mui/icons-material";
import { useTranslation } from "react-i18next";
import { inventoryService } from "../services/warehouseService";
import { InventoryStatus, InventoryCountLineDto } from "../types";
import dayjs from "dayjs";

export default function InventoryCountPage() {
  const { t } = useTranslation();
  const { id } = useParams();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const inventoryId = Number(id);

  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);

  const { data: inventory, isLoading } = useQuery({
    queryKey: ["inventory", inventoryId],
    queryFn: () => inventoryService.getById(inventoryId),
  });

  const startMutation = useMutation({
    mutationFn: () => inventoryService.start(inventoryId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["inventory", inventoryId] });
    },
  });

  const completeMutation = useMutation({
    mutationFn: () => inventoryService.complete(inventoryId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["inventory", inventoryId] });
    },
  });

  const confirmMutation = useMutation({
    mutationFn: () => inventoryService.confirm(inventoryId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["inventory", inventoryId] });
      setConfirmDialogOpen(false);
      navigate("/warehouse/inventory");
    },
  });

  const updateLineMutation = useMutation({
    mutationFn: ({
      lineId,
      quantity,
    }: {
      lineId: number;
      quantity: number;
    }) => inventoryService.updateLine(lineId, quantity),
    onSuccess: () => {
      // Optimistic update or invalidate
      queryClient.invalidateQueries({ queryKey: ["inventory", inventoryId] });
    },
  });

  const handleProcessRowUpdate = async (newRow: GridRowModel) => {
    const line = newRow as InventoryCountLineDto;
    if (line.countedQuantity !== undefined && line.countedQuantity !== null) {
      await updateLineMutation.mutateAsync({
        lineId: line.id,
        quantity: Number(line.countedQuantity),
      });
    }
    return newRow;
  };

  if (isLoading || !inventory) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  const isEditable = inventory.status === InventoryStatus.InProgress;

  const columns: GridColDef[] = [
    { field: "articleCode", headerName: t("warehouse.inventory.count.columns.articleCode"), width: 150 },
    {
      field: "articleDescription",
      headerName: t("warehouse.inventory.count.columns.description"),
      flex: 1,
      minWidth: 200,
    },
    { field: "batchNumber", headerName: t("warehouse.inventory.count.columns.batch"), width: 120 },
    { field: "locationCode", headerName: t("warehouse.inventory.count.columns.location"), width: 120 },
    {
      field: "theoreticalQuantity",
      headerName: t("warehouse.inventory.count.columns.theoreticalQty"),
      width: 120,
      type: "number",
      valueFormatter: (value) => (value ? Number(value).toFixed(2) : "0"),
    },
    {
      field: "countedQuantity",
      headerName: t("warehouse.inventory.count.columns.countedQty"),
      width: 150,
      type: "number",
      editable: isEditable,
      cellClassName: isEditable ? "editable-cell" : "",
      valueFormatter: (value) =>
        value !== undefined && value !== null
          ? Number(value).toFixed(2)
          : "-",
    },
    {
      field: "difference",
      headerName: t("warehouse.inventory.count.columns.difference"),
      width: 120,
      type: "number",
      valueGetter: (_value, row) => {
        if (
          row.countedQuantity === undefined ||
          row.countedQuantity === null
        )
          return null;
        return row.countedQuantity - row.theoreticalQuantity;
      },
      renderCell: (params: GridRenderCellParams) => {
        if (params.value === null || params.value === undefined) return "-";
        const val = Number(params.value);
        return (
          <Typography
            color={val === 0 ? "text.primary" : val < 0 ? "error" : "success"}
            fontWeight={val !== 0 ? "bold" : "normal"}
          >
            {val > 0 ? "+" : ""}
            {val.toFixed(2)}
          </Typography>
        );
      },
    },
  ];

  return (
    <Box sx={{ p: 3 }}>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 3,
        }}
      >
        <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
          <Button
            startIcon={<ArrowBackIcon />}
            onClick={() => navigate("/warehouse/inventory")}
          >
            {t("warehouse.inventory.count.actions.back")}
          </Button>
          <Typography variant="h4">
            {t("warehouse.inventory.count.title", { description: inventory.description })}
          </Typography>
          <Chip
            label={inventory.status}
            color={
              inventory.status === InventoryStatus.Confirmed
                ? "success"
                : inventory.status === InventoryStatus.InProgress
                  ? "primary"
                  : "default"
            }
          />
        </Box>
        <Box sx={{ display: "flex", gap: 2 }}>
          {inventory.status === InventoryStatus.Draft && (
            <Button
              variant="contained"
              color="primary"
              startIcon={<StartIcon />}
              onClick={() => startMutation.mutate()}
            >
              {t("warehouse.inventory.count.actions.start")}
            </Button>
          )}
          {inventory.status === InventoryStatus.InProgress && (
            <Button
              variant="contained"
              color="warning"
              startIcon={<CompleteIcon />}
              onClick={() => completeMutation.mutate()}
            >
              {t("warehouse.inventory.count.actions.complete")}
            </Button>
          )}
          {inventory.status === InventoryStatus.Completed && (
            <Button
              variant="contained"
              color="success"
              startIcon={<ConfirmIcon />}
              onClick={() => setConfirmDialogOpen(true)}
            >
              {t("warehouse.inventory.count.actions.confirm")}
            </Button>
          )}
        </Box>
      </Box>

      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid size={{ xs: 12, md: 3 }}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                {t("warehouse.inventory.count.cards.date")}
              </Typography>
              <Typography variant="h6">
                {dayjs(inventory.inventoryDate).format("DD/MM/YYYY")}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, md: 3 }}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                {t("warehouse.inventory.count.cards.warehouse")}
              </Typography>
              <Typography variant="h6">{inventory.warehouseName}</Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, md: 3 }}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                {t("warehouse.inventory.count.cards.totalLines")}
              </Typography>
              <Typography variant="h6">{inventory.lineCount}</Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, md: 3 }}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                {t("warehouse.inventory.count.cards.countedLines")}
              </Typography>
              <Typography variant="h6">
                {inventory.lines.filter((l) => l.countedQuantity !== null).length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {inventory.status === InventoryStatus.Completed && (
        <Alert severity="warning" sx={{ mb: 3 }}>
          {t("warehouse.inventory.count.alert.completed")}
        </Alert>
      )}

      <Paper sx={{ height: 600, width: "100%" }}>
        <DataGrid
          rows={inventory.lines}
          columns={columns}
          processRowUpdate={handleProcessRowUpdate}
          onProcessRowUpdateError={(error) => console.error(error)}
          slots={{ toolbar: GridToolbar }}
          slotProps={{
            toolbar: {
              showQuickFilter: true,
            },
          }}
          disableRowSelectionOnClick
          sx={{
            "& .editable-cell": {
              backgroundColor: "#f0f8ff",
            },
          }}
        />
      </Paper>

      <Dialog
        open={confirmDialogOpen}
        onClose={() => setConfirmDialogOpen(false)}
      >
        <DialogTitle>{t("warehouse.inventory.count.confirmDialog.title")}</DialogTitle>
        <DialogContent>
          <DialogContentText>
            {t("warehouse.inventory.count.confirmDialog.content")}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmDialogOpen(false)}>{t("warehouse.inventory.count.confirmDialog.cancel")}</Button>
          <Button
            onClick={() => confirmMutation.mutate()}
            color="success"
            variant="contained"
            autoFocus
          >
            {t("warehouse.inventory.count.confirmDialog.confirm")}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
