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 { inventoryService } from "../services/warehouseService";
import { InventoryStatus, InventoryCountLineDto } from "../types";
import dayjs from "dayjs";

export default function InventoryCountPage() {
  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: "Codice Articolo", width: 150 },
    {
      field: "articleDescription",
      headerName: "Descrizione",
      flex: 1,
      minWidth: 200,
    },
    { field: "batchNumber", headerName: "Lotto", width: 120 },
    { field: "locationCode", headerName: "Ubicazione", width: 120 },
    {
      field: "theoreticalQuantity",
      headerName: "Qta Teorica",
      width: 120,
      type: "number",
      valueFormatter: (value) => (value ? Number(value).toFixed(2) : "0"),
    },
    {
      field: "countedQuantity",
      headerName: "Qta Contata",
      width: 150,
      type: "number",
      editable: isEditable,
      cellClassName: isEditable ? "editable-cell" : "",
      valueFormatter: (value) =>
        value !== undefined && value !== null
          ? Number(value).toFixed(2)
          : "-",
    },
    {
      field: "difference",
      headerName: "Differenza",
      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")}
          >
            Indietro
          </Button>
          <Typography variant="h4">
            Inventario: {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()}
            >
              Avvia Inventario
            </Button>
          )}
          {inventory.status === InventoryStatus.InProgress && (
            <Button
              variant="contained"
              color="warning"
              startIcon={<CompleteIcon />}
              onClick={() => completeMutation.mutate()}
            >
              Completa Conteggio
            </Button>
          )}
          {inventory.status === InventoryStatus.Completed && (
            <Button
              variant="contained"
              color="success"
              startIcon={<ConfirmIcon />}
              onClick={() => setConfirmDialogOpen(true)}
            >
              Conferma e Rettifica
            </Button>
          )}
        </Box>
      </Box>

      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid size={{ xs: 12, md: 3 }}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                Data Inventario
              </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>
                Magazzino
              </Typography>
              <Typography variant="h6">{inventory.warehouseName}</Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, md: 3 }}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                Righe Totali
              </Typography>
              <Typography variant="h6">{inventory.lineCount}</Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, md: 3 }}>
          <Card>
            <CardContent>
              <Typography color="text.secondary" gutterBottom>
                Righe Contate
              </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 }}>
          L'inventario è completato. Verifica le differenze prima di confermare.
          La conferma genererà automaticamente i movimenti di rettifica.
        </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>Conferma Inventario</DialogTitle>
        <DialogContent>
          <DialogContentText>
            Sei sicuro di voler confermare l'inventario? Questa operazione è
            irreversibile e genererà i movimenti di rettifica per le differenze
            riscontrate.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmDialogOpen(false)}>Annulla</Button>
          <Button
            onClick={() => confirmMutation.mutate()}
            color="success"
            variant="contained"
            autoFocus
          >
            Conferma
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
