import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Box,
  Typography,
  Button,
  Paper,
  Grid,
  TextField,
  MenuItem,
  FormControl,
  InputLabel,
  Select,
  Breadcrumbs,
  Link,
  CircularProgress,
} from "@mui/material";
import { Save as SaveIcon, ArrowBack as ArrowBackIcon } from "@mui/icons-material";
import {
  inventoryService,
  warehouseLocationService,
  categoryService,
} from "../services/warehouseService";
import {
  CreateInventoryCountDto,
  InventoryType,
} from "../types";
import dayjs from "dayjs";

export default function InventoryFormPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const isEditing = !!id;

  const [formData, setFormData] = useState<CreateInventoryCountDto>({
    description: "",
    inventoryDate: dayjs().format("YYYY-MM-DD"),
    type: InventoryType.Full,
    notes: "",
  });

  const { data: warehouses = [] } = useQuery({
    queryKey: ["warehouse-locations"],
    queryFn: () => warehouseLocationService.getAll(),
  });

  const { data: categories = [] } = useQuery({
    queryKey: ["categories"],
    queryFn: () => categoryService.getAll(),
  });

  const { data: inventory, isLoading: isLoadingInventory } = useQuery({
    queryKey: ["inventory", id],
    queryFn: () => inventoryService.getById(Number(id)),
    enabled: isEditing,
  });

  useEffect(() => {
    if (inventory) {
      setFormData({
        description: inventory.description,
        inventoryDate: dayjs(inventory.inventoryDate).format("YYYY-MM-DD"),
        warehouseId: inventory.warehouseId,
        categoryId: inventory.categoryId,
        type: inventory.type,
        notes: inventory.notes,
      });
    }
  }, [inventory]);

  const createMutation = useMutation({
    mutationFn: (data: CreateInventoryCountDto) => inventoryService.create(data),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ["inventory-counts"] });
      navigate(`/warehouse/inventory/${data.id}/count`);
    },
  });

  // TODO: Add update mutation if needed, currently only creation is critical

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (isEditing) {
      // Implement update logic if needed
    } else {
      createMutation.mutate(formData);
    }
  };

  if (isEditing && isLoadingInventory) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <Breadcrumbs sx={{ mb: 2 }}>
        <Link
          color="inherit"
          href="#"
          onClick={(e) => {
            e.preventDefault();
            navigate("/warehouse/inventory");
          }}
        >
          Inventari
        </Link>
        <Typography color="text.primary">
          {isEditing ? "Modifica Inventario" : "Nuovo Inventario"}
        </Typography>
      </Breadcrumbs>

      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 3,
        }}
      >
        <Typography variant="h4">
          {isEditing ? `Inventario ${inventory?.code}` : "Nuovo Inventario"}
        </Typography>
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate("/warehouse/inventory")}
        >
          Indietro
        </Button>
      </Box>

      <Paper sx={{ p: 3 }}>
        <form onSubmit={handleSubmit}>
          <Grid container spacing={3}>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Descrizione"
                fullWidth
                required
                value={formData.description}
                onChange={(e) =>
                  setFormData({ ...formData, description: e.target.value })
                }
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <TextField
                label="Data Inventario"
                type="date"
                fullWidth
                required
                InputLabelProps={{ shrink: true }}
                value={formData.inventoryDate}
                onChange={(e) =>
                  setFormData({ ...formData, inventoryDate: e.target.value })
                }
              />
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <FormControl fullWidth required>
                <InputLabel>Magazzino</InputLabel>
                <Select
                  value={formData.warehouseId || ""}
                  label="Magazzino"
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      warehouseId: Number(e.target.value),
                    })
                  }
                  disabled={isEditing} // Cannot change warehouse after creation usually
                >
                  {warehouses.map((w) => (
                    <MenuItem key={w.id} value={w.id}>
                      {w.name} ({w.code})
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <FormControl fullWidth>
                <InputLabel>Categoria (Opzionale)</InputLabel>
                <Select
                  value={formData.categoryId || ""}
                  label="Categoria (Opzionale)"
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      categoryId: e.target.value ? Number(e.target.value) : undefined,
                    })
                  }
                >
                  <MenuItem value="">
                    <em>Tutte</em>
                  </MenuItem>
                  {categories.map((c) => (
                    <MenuItem key={c.id} value={c.id}>
                      {c.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 12, md: 6 }}>
              <FormControl fullWidth required>
                <InputLabel>Tipo Inventario</InputLabel>
                <Select
                  value={formData.type}
                  label="Tipo Inventario"
                  onChange={(e) =>
                    setFormData({
                      ...formData,
                      type: Number(e.target.value) as InventoryType,
                    })
                  }
                >
                  <MenuItem value={InventoryType.Full}>Completo</MenuItem>
                  <MenuItem value={InventoryType.Partial}>Parziale</MenuItem>
                  <MenuItem value={InventoryType.Cyclic}>Ciclico</MenuItem>
                  <MenuItem value={InventoryType.Sample}>A Campione</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid size={{ xs: 12 }}>
              <TextField
                label="Note"
                fullWidth
                multiline
                rows={4}
                value={formData.notes || ""}
                onChange={(e) =>
                  setFormData({ ...formData, notes: e.target.value })
                }
              />
            </Grid>
            <Grid size={{ xs: 12 }} sx={{ display: "flex", justifyContent: "flex-end" }}>
              <Button
                type="submit"
                variant="contained"
                size="large"
                startIcon={<SaveIcon />}
                disabled={createMutation.isPending}
              >
                {isEditing ? "Salva Modifiche" : "Crea e Inizia"}
              </Button>
            </Grid>
          </Grid>
        </form>
      </Paper>
    </Box>
  );
}
