import React, { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Box,
  Paper,
  Typography,
  Grid,
  TextField,
  Button,
  Tabs,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Autocomplete,
  Chip,
  CircularProgress,
  Divider,
  Card,
  CardContent,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
} from "@mui/material";
import {
  Save as SaveIcon,
  ArrowBack as BackIcon,
  Add as AddIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
  ContentCopy as CopyIcon,
  Refresh as RefreshIcon,
  CheckCircle as ConfirmIcon,
  Print as PrintIcon,
} from "@mui/icons-material";
import dayjs from "dayjs";
import {
  eventiApi,
  clientiApi,
  locationApi,
  tipiEventoApi,
  articoliApi,
  risorseApi,
} from "../services/api";
import type { Evento } from "../types";
import {
  StatoEvento,
  getStatoLabel,
  getStatoColor,
  getStatoTextColor,
  formatCurrency,
} from "../types";
import EventoCostiPanel from "../components/EventoCostiPanel";

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;
  return (
    <div role="tabpanel" hidden={value !== index} {...other}>
      {value === index && <Box sx={{ p: 2 }}>{children}</Box>}
    </div>
  );
}

const EventoDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const isNew = id === "nuovo";

  // State
  const [tabValue, setTabValue] = useState(0);
  const [formData, setFormData] = useState<Partial<Evento>>({
    dataEvento: dayjs().format("YYYY-MM-DD"),
    stato: StatoEvento.Scheda,
  });
  const [dialogOpen, setDialogOpen] = useState<string | null>(null);

  // Queries
  const { data: evento, isLoading } = useQuery({
    queryKey: ["evento", id],
    queryFn: () => eventiApi.getById(Number(id)),
    enabled: !isNew && !!id,
  });

  const { data: clienti } = useQuery({
    queryKey: ["clienti"],
    queryFn: clientiApi.getAll,
  });

  const { data: locations } = useQuery({
    queryKey: ["location"],
    queryFn: locationApi.getAll,
  });

  const { data: tipiEvento } = useQuery({
    queryKey: ["tipiEvento"],
    queryFn: tipiEventoApi.getAll,
  });

  const { data: articoli } = useQuery({
    queryKey: ["articoli"],
    queryFn: articoliApi.getAll,
  });

  const { data: risorse } = useQuery({
    queryKey: ["risorse"],
    queryFn: risorseApi.getAll,
  });

  // Set form data when evento is loaded
  React.useEffect(() => {
    if (evento) {
      setFormData(evento);
    }
  }, [evento]);

  // Mutations
  const saveMutation = useMutation({
    mutationFn: (data: Partial<Evento>) =>
      isNew ? eventiApi.create(data) : eventiApi.update(Number(id), data),
    onSuccess: (savedEvento) => {
      queryClient.invalidateQueries({ queryKey: ["eventi"] });
      queryClient.invalidateQueries({ queryKey: ["evento", id] });
      if (isNew) {
        navigate(`/eventi/${savedEvento.id}`);
      }
    },
  });

  const duplicateMutation = useMutation({
    mutationFn: () => eventiApi.duplicate(Number(id)),
    onSuccess: (newEvento) => {
      queryClient.invalidateQueries({ queryKey: ["eventi"] });
      navigate(`/eventi/${newEvento.id}`);
    },
  });

  const ricalcolaQuantitaMutation = useMutation({
    mutationFn: () => eventiApi.ricalcolaQuantita(Number(id)),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento", id] });
    },
  });

  const confermaMutation = useMutation({
    mutationFn: () => eventiApi.conferma(Number(id)),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento", id] });
      queryClient.invalidateQueries({ queryKey: ["eventi"] });
    },
  });

  const handleSave = () => {
    saveMutation.mutate(formData);
  };

  const handleFieldChange = (field: keyof Evento, value: any) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const currentStato = formData.stato ?? StatoEvento.Scheda;

  if (isLoading && !isNew) {
    return (
      <Box
        display="flex"
        justifyContent="center"
        alignItems="center"
        minHeight="400px"
      >
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      {/* Header with status color */}
      <Paper
        sx={{
          p: 2,
          mb: 3,
          backgroundColor: getStatoColor(currentStato),
          borderLeft: `6px solid ${getStatoTextColor(currentStato)}`,
        }}
      >
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Box display="flex" alignItems="center" gap={2}>
            <IconButton onClick={() => navigate("/eventi")}>
              <BackIcon />
            </IconButton>
            <Box>
              <Typography
                variant="h5"
                sx={{ color: getStatoTextColor(currentStato) }}
              >
                {isNew ? "Nuovo Evento" : `Evento ${formData.codice || ""}`}
              </Typography>
              <Typography variant="body2" color="textSecondary">
                {formData.dataEvento &&
                  dayjs(formData.dataEvento).format("dddd DD MMMM YYYY")}
              </Typography>
            </Box>
            <Chip
              label={getStatoLabel(currentStato)}
              sx={{
                backgroundColor: getStatoTextColor(currentStato),
                color: "white",
                fontWeight: "bold",
              }}
            />
          </Box>
          <Box display="flex" gap={1}>
            {!isNew && (
              <>
                <Button
                  variant="outlined"
                  startIcon={<CopyIcon />}
                  onClick={() => duplicateMutation.mutate()}
                  disabled={duplicateMutation.isPending}
                >
                  Duplica
                </Button>
                <Button
                  variant="outlined"
                  startIcon={<RefreshIcon />}
                  onClick={() => ricalcolaQuantitaMutation.mutate()}
                  disabled={ricalcolaQuantitaMutation.isPending}
                >
                  Ricalcola Qta
                </Button>
                {currentStato !== StatoEvento.Confermato && (
                  <Button
                    variant="outlined"
                    color="success"
                    startIcon={<ConfirmIcon />}
                    onClick={() => confermaMutation.mutate()}
                    disabled={confermaMutation.isPending}
                  >
                    Conferma
                  </Button>
                )}
                <Button variant="outlined" startIcon={<PrintIcon />}>
                  Stampa
                </Button>
              </>
            )}
            <Button
              variant="contained"
              startIcon={<SaveIcon />}
              onClick={handleSave}
              disabled={saveMutation.isPending}
            >
              Salva
            </Button>
          </Box>
        </Box>
      </Paper>

      {saveMutation.isError && (
        <Alert severity="error" sx={{ mb: 2 }}>
          Errore durante il salvataggio
        </Alert>
      )}

      {saveMutation.isSuccess && (
        <Alert severity="success" sx={{ mb: 2 }}>
          Evento salvato con successo
        </Alert>
      )}

      <Grid container spacing={3}>
        {/* Left column - Main data */}
        <Grid size={{ xs: 12, md: 8 }}>
          <Paper sx={{ p: 2, mb: 3 }}>
            <Typography
              variant="h6"
              gutterBottom
              sx={{
                color: "#1976d2",
                borderBottom: "2px solid #1976d2",
                pb: 1,
              }}
            >
              Dati Evento
            </Typography>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid size={{ xs: 12, sm: 6, md: 3 }}>
                <TextField
                  fullWidth
                  label="Data Evento"
                  type="date"
                  value={formData.dataEvento?.split("T")[0] || ""}
                  onChange={(e) =>
                    handleFieldChange("dataEvento", e.target.value)
                  }
                  InputLabelProps={{ shrink: true }}
                  size="small"
                />
              </Grid>
              <Grid size={{ xs: 6, sm: 3, md: 2 }}>
                <TextField
                  fullWidth
                  label="Ora Inizio"
                  type="time"
                  value={formData.oraInizio || ""}
                  onChange={(e) =>
                    handleFieldChange("oraInizio", e.target.value)
                  }
                  InputLabelProps={{ shrink: true }}
                  size="small"
                />
              </Grid>
              <Grid size={{ xs: 6, sm: 3, md: 2 }}>
                <TextField
                  fullWidth
                  label="Ora Fine"
                  type="time"
                  value={formData.oraFine || ""}
                  onChange={(e) => handleFieldChange("oraFine", e.target.value)}
                  InputLabelProps={{ shrink: true }}
                  size="small"
                />
              </Grid>
              <Grid size={{ xs: 12, sm: 6, md: 5 }}>
                <FormControl fullWidth size="small">
                  <InputLabel>Tipo Evento</InputLabel>
                  <Select
                    value={formData.tipoEventoId || ""}
                    label="Tipo Evento"
                    onChange={(e) =>
                      handleFieldChange("tipoEventoId", e.target.value)
                    }
                  >
                    <MenuItem value="">-- Seleziona --</MenuItem>
                    {tipiEvento?.map((tipo) => (
                      <MenuItem key={tipo.id} value={tipo.id}>
                        {tipo.descrizione}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
              <Grid size={{ xs: 12, md: 6 }}>
                <Autocomplete
                  options={clienti || []}
                  getOptionLabel={(option) => option.ragioneSociale}
                  value={
                    clienti?.find((c) => c.id === formData.clienteId) || null
                  }
                  onChange={(_, newValue) =>
                    handleFieldChange("clienteId", newValue?.id || null)
                  }
                  renderInput={(params) => (
                    <TextField {...params} label="Cliente" size="small" />
                  )}
                />
              </Grid>
              <Grid size={{ xs: 12, md: 6 }}>
                <Autocomplete
                  options={locations || []}
                  getOptionLabel={(option) =>
                    `${option.nome}${option.citta ? ` - ${option.citta}` : ""}`
                  }
                  value={
                    locations?.find((l) => l.id === formData.locationId) || null
                  }
                  onChange={(_, newValue) =>
                    handleFieldChange("locationId", newValue?.id || null)
                  }
                  renderInput={(params) => (
                    <TextField {...params} label="Location" size="small" />
                  )}
                />
              </Grid>
              <Grid size={{ xs: 12 }}>
                <TextField
                  fullWidth
                  label="Descrizione"
                  value={formData.descrizione || ""}
                  onChange={(e) =>
                    handleFieldChange("descrizione", e.target.value)
                  }
                  size="small"
                />
              </Grid>
            </Grid>
          </Paper>

          {/* Tabs for details */}
          <Paper>
            <Tabs
              value={tabValue}
              onChange={(_, v) => setTabValue(v)}
              sx={{
                borderBottom: 1,
                borderColor: "divider",
                backgroundColor: "#f5f5f5",
              }}
            >
              <Tab label="Ospiti" />
              <Tab label="Lista Prelievo" />
              <Tab label="Risorse" />
              <Tab label="Acconti" />
              <Tab label="Note" />
            </Tabs>

            {/* Tab: Ospiti */}
            <TabPanel value={tabValue} index={0}>
              <Box display="flex" justifyContent="space-between" mb={2}>
                <Typography variant="subtitle1" fontWeight="bold">
                  Numero Ospiti
                </Typography>
              </Box>
              <Grid container spacing={2}>
                <Grid size={{ xs: 6, sm: 3 }}>
                  <TextField
                    fullWidth
                    label="Totale Ospiti"
                    type="number"
                    value={formData.numeroOspiti || ""}
                    onChange={(e) =>
                      handleFieldChange("numeroOspiti", Number(e.target.value))
                    }
                    size="small"
                  />
                </Grid>
                <Grid size={{ xs: 6, sm: 3 }}>
                  <TextField
                    fullWidth
                    label="Adulti"
                    type="number"
                    value={formData.numeroOspitiAdulti || ""}
                    onChange={(e) =>
                      handleFieldChange(
                        "numeroOspitiAdulti",
                        Number(e.target.value),
                      )
                    }
                    size="small"
                  />
                </Grid>
                <Grid size={{ xs: 6, sm: 3 }}>
                  <TextField
                    fullWidth
                    label="Bambini"
                    type="number"
                    value={formData.numeroOspitiBambini || ""}
                    onChange={(e) =>
                      handleFieldChange(
                        "numeroOspitiBambini",
                        Number(e.target.value),
                      )
                    }
                    size="small"
                  />
                </Grid>
                <Grid size={{ xs: 6, sm: 3 }}>
                  <TextField
                    fullWidth
                    label="Seduti"
                    type="number"
                    value={formData.numeroOspitiSeduti || ""}
                    onChange={(e) =>
                      handleFieldChange(
                        "numeroOspitiSeduti",
                        Number(e.target.value),
                      )
                    }
                    size="small"
                  />
                </Grid>
                <Grid size={{ xs: 6, sm: 3 }}>
                  <TextField
                    fullWidth
                    label="Buffet"
                    type="number"
                    value={formData.numeroOspitiBuffet || ""}
                    onChange={(e) =>
                      handleFieldChange(
                        "numeroOspitiBuffet",
                        Number(e.target.value),
                      )
                    }
                    size="small"
                  />
                </Grid>
              </Grid>
            </TabPanel>

            {/* Tab: Lista Prelievo */}
            <TabPanel value={tabValue} index={1}>
              <Box display="flex" justifyContent="space-between" mb={2}>
                <Typography variant="subtitle1" fontWeight="bold">
                  Articoli da Prelevare
                </Typography>
                <Button
                  size="small"
                  startIcon={<AddIcon />}
                  onClick={() => setDialogOpen("prelievo")}
                >
                  Aggiungi Articolo
                </Button>
              </Box>
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow sx={{ backgroundColor: "#e3f2fd" }}>
                      <TableCell>Codice</TableCell>
                      <TableCell>Descrizione</TableCell>
                      <TableCell align="right">Qta Richiesta</TableCell>
                      <TableCell align="right">Qta Prelevata</TableCell>
                      <TableCell>Note</TableCell>
                      <TableCell align="center">Azioni</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {evento?.dettagliPrelievo?.map((det) => (
                      <TableRow key={det.id} hover>
                        <TableCell>{det.articolo?.codice}</TableCell>
                        <TableCell>{det.articolo?.descrizione}</TableCell>
                        <TableCell align="right">
                          {det.quantitaRichiesta}
                        </TableCell>
                        <TableCell align="right">
                          {det.quantitaPrelevata || "-"}
                        </TableCell>
                        <TableCell>{det.note || "-"}</TableCell>
                        <TableCell align="center">
                          <IconButton size="small">
                            <EditIcon fontSize="small" />
                          </IconButton>
                          <IconButton size="small" color="error">
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    ))}
                    {(!evento?.dettagliPrelievo ||
                      evento.dettagliPrelievo.length === 0) && (
                      <TableRow>
                        <TableCell colSpan={6} align="center">
                          <Typography color="textSecondary">
                            Nessun articolo
                          </Typography>
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            </TabPanel>

            {/* Tab: Risorse */}
            <TabPanel value={tabValue} index={2}>
              <Box display="flex" justifyContent="space-between" mb={2}>
                <Typography variant="subtitle1" fontWeight="bold">
                  Risorse Assegnate
                </Typography>
                <Button
                  size="small"
                  startIcon={<AddIcon />}
                  onClick={() => setDialogOpen("risorsa")}
                >
                  Aggiungi Risorsa
                </Button>
              </Box>
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow sx={{ backgroundColor: "#e3f2fd" }}>
                      <TableCell>Nome</TableCell>
                      <TableCell>Cognome</TableCell>
                      <TableCell>Tipo</TableCell>
                      <TableCell>Ora Inizio</TableCell>
                      <TableCell>Ora Fine</TableCell>
                      <TableCell>Note</TableCell>
                      <TableCell align="center">Azioni</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {evento?.dettagliRisorse?.map((det) => (
                      <TableRow key={det.id} hover>
                        <TableCell>{det.risorsa?.nome}</TableCell>
                        <TableCell>{det.risorsa?.cognome || "-"}</TableCell>
                        <TableCell>
                          {det.risorsa?.tipoRisorsa?.descrizione || "-"}
                        </TableCell>
                        <TableCell>{det.oraInizio || "-"}</TableCell>
                        <TableCell>{det.oraFine || "-"}</TableCell>
                        <TableCell>{det.note || "-"}</TableCell>
                        <TableCell align="center">
                          <IconButton size="small">
                            <EditIcon fontSize="small" />
                          </IconButton>
                          <IconButton size="small" color="error">
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    ))}
                    {(!evento?.dettagliRisorse ||
                      evento.dettagliRisorse.length === 0) && (
                      <TableRow>
                        <TableCell colSpan={7} align="center">
                          <Typography color="textSecondary">
                            Nessuna risorsa assegnata
                          </Typography>
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            </TabPanel>

            {/* Tab: Acconti */}
            <TabPanel value={tabValue} index={3}>
              <Box display="flex" justifyContent="space-between" mb={2}>
                <Typography variant="subtitle1" fontWeight="bold">
                  Acconti Ricevuti
                </Typography>
                <Button
                  size="small"
                  startIcon={<AddIcon />}
                  onClick={() => setDialogOpen("acconto")}
                >
                  Aggiungi Acconto
                </Button>
              </Box>
              <TableContainer>
                <Table size="small">
                  <TableHead>
                    <TableRow sx={{ backgroundColor: "#e3f2fd" }}>
                      <TableCell>Data</TableCell>
                      <TableCell>Descrizione</TableCell>
                      <TableCell align="right">Importo</TableCell>
                      <TableCell>Metodo Pagamento</TableCell>
                      <TableCell align="center">Azioni</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {evento?.acconti?.map((acc) => (
                      <TableRow key={acc.id} hover>
                        <TableCell>
                          {dayjs(acc.dataAcconto).format("DD/MM/YYYY")}
                        </TableCell>
                        <TableCell>{acc.descrizione || "-"}</TableCell>
                        <TableCell align="right">
                          {acc.importo?.toLocaleString("it-IT", {
                            style: "currency",
                            currency: "EUR",
                          })}
                        </TableCell>
                        <TableCell>{acc.metodoPagamento || "-"}</TableCell>
                        <TableCell align="center">
                          <IconButton size="small">
                            <EditIcon fontSize="small" />
                          </IconButton>
                          <IconButton size="small" color="error">
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    ))}
                    {(!evento?.acconti || evento.acconti.length === 0) && (
                      <TableRow>
                        <TableCell colSpan={5} align="center">
                          <Typography color="textSecondary">
                            Nessun acconto
                          </Typography>
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            </TabPanel>

            {/* Tab: Note */}
            <TabPanel value={tabValue} index={4}>
              <Grid container spacing={2}>
                <Grid size={{ xs: 12, md: 6 }}>
                  <TextField
                    fullWidth
                    label="Note Interne"
                    multiline
                    rows={4}
                    value={formData.noteInterne || ""}
                    onChange={(e) =>
                      handleFieldChange("noteInterne", e.target.value)
                    }
                  />
                </Grid>
                <Grid size={{ xs: 12, md: 6 }}>
                  <TextField
                    fullWidth
                    label="Note Cliente"
                    multiline
                    rows={4}
                    value={formData.noteCliente || ""}
                    onChange={(e) =>
                      handleFieldChange("noteCliente", e.target.value)
                    }
                  />
                </Grid>
                <Grid size={{ xs: 12, md: 6 }}>
                  <TextField
                    fullWidth
                    label="Note Cucina"
                    multiline
                    rows={4}
                    value={formData.noteCucina || ""}
                    onChange={(e) =>
                      handleFieldChange("noteCucina", e.target.value)
                    }
                  />
                </Grid>
                <Grid size={{ xs: 12, md: 6 }}>
                  <TextField
                    fullWidth
                    label="Note Allestimento"
                    multiline
                    rows={4}
                    value={formData.noteAllestimento || ""}
                    onChange={(e) =>
                      handleFieldChange("noteAllestimento", e.target.value)
                    }
                  />
                </Grid>
              </Grid>
            </TabPanel>
          </Paper>
        </Grid>

        {/* Right column - Summary */}
        <Grid size={{ xs: 12, md: 4 }}>
          <Card sx={{ mb: 2 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom sx={{ color: "#1976d2" }}>
                Riepilogo Economico
              </Typography>
              <Divider sx={{ mb: 2 }} />
              <Box display="flex" justifyContent="space-between" mb={1}>
                <Typography>Costo Totale:</Typography>
                <Typography fontWeight="bold">
                  {formData.costoTotale?.toLocaleString("it-IT", {
                    style: "currency",
                    currency: "EUR",
                  }) || "€ 0,00"}
                </Typography>
              </Box>
              <Box display="flex" justifyContent="space-between" mb={1}>
                <Typography>Costo per Persona:</Typography>
                <Typography>
                  {formData.costoPersona?.toLocaleString("it-IT", {
                    style: "currency",
                    currency: "EUR",
                  }) || "€ 0,00"}
                </Typography>
              </Box>
              <Divider sx={{ my: 1 }} />
              <Box display="flex" justifyContent="space-between" mb={1}>
                <Typography>Totale Acconti:</Typography>
                <Typography color="success.main">
                  {formData.totaleAcconti?.toLocaleString("it-IT", {
                    style: "currency",
                    currency: "EUR",
                  }) || "€ 0,00"}
                </Typography>
              </Box>
              <Box display="flex" justifyContent="space-between">
                <Typography fontWeight="bold">Saldo:</Typography>
                <Typography fontWeight="bold" color="error.main">
                  {formData.saldo?.toLocaleString("it-IT", {
                    style: "currency",
                    currency: "EUR",
                  }) || "€ 0,00"}
                </Typography>
              </Box>
            </CardContent>
          </Card>

          <Card sx={{ mb: 2 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom sx={{ color: "#1976d2" }}>
                Info Cliente
              </Typography>
              <Divider sx={{ mb: 2 }} />
              {formData.clienteId && evento?.cliente ? (
                <>
                  <Typography variant="body1" fontWeight="bold">
                    {evento.cliente.ragioneSociale}
                  </Typography>
                  {evento.cliente.indirizzo && (
                    <Typography variant="body2" color="textSecondary">
                      {evento.cliente.indirizzo}
                    </Typography>
                  )}
                  {evento.cliente.citta && (
                    <Typography variant="body2" color="textSecondary">
                      {evento.cliente.cap} {evento.cliente.citta} (
                      {evento.cliente.provincia})
                    </Typography>
                  )}
                  {evento.cliente.telefono && (
                    <Typography variant="body2">
                      Tel: {evento.cliente.telefono}
                    </Typography>
                  )}
                  {evento.cliente.email && (
                    <Typography variant="body2">
                      Email: {evento.cliente.email}
                    </Typography>
                  )}
                </>
              ) : (
                <Typography color="textSecondary">
                  Nessun cliente selezionato
                </Typography>
              )}
            </CardContent>
          </Card>

          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom sx={{ color: "#1976d2" }}>
                Info Location
              </Typography>
              <Divider sx={{ mb: 2 }} />
              {formData.locationId && evento?.location ? (
                <>
                  <Typography variant="body1" fontWeight="bold">
                    {evento.location.nome}
                  </Typography>
                  {evento.location.indirizzo && (
                    <Typography variant="body2" color="textSecondary">
                      {evento.location.indirizzo}
                    </Typography>
                  )}
                  {evento.location.citta && (
                    <Typography variant="body2" color="textSecondary">
                      {evento.location.cap} {evento.location.citta} (
                      {evento.location.provincia})
                    </Typography>
                  )}
                  {evento.location.distanzaKm && (
                    <Typography variant="body2">
                      Distanza: {evento.location.distanzaKm} km
                    </Typography>
                  )}
                  {evento.location.referente && (
                    <Typography variant="body2">
                      Referente: {evento.location.referente}
                    </Typography>
                  )}
                </>
              ) : (
                <Typography color="textSecondary">
                  Nessuna location selezionata
                </Typography>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Dialog: Aggiungi Articolo */}
      <Dialog
        open={dialogOpen === "prelievo"}
        onClose={() => setDialogOpen(null)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Aggiungi Articolo</DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2 }}>
            <Autocomplete
              options={articoli || []}
              getOptionLabel={(option) =>
                `${option.codice} - ${option.descrizione}`
              }
              renderInput={(params) => (
                <TextField {...params} label="Articolo" fullWidth />
              )}
              sx={{ mb: 2 }}
            />
            <TextField
              fullWidth
              label="Quantita Richiesta"
              type="number"
              sx={{ mb: 2 }}
            />
            <TextField fullWidth label="Note" multiline rows={2} />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(null)}>Annulla</Button>
          <Button variant="contained">Aggiungi</Button>
        </DialogActions>
      </Dialog>

      {/* Dialog: Aggiungi Risorsa */}
      <Dialog
        open={dialogOpen === "risorsa"}
        onClose={() => setDialogOpen(null)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Aggiungi Risorsa</DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2 }}>
            <Autocomplete
              options={risorse || []}
              getOptionLabel={(option) =>
                `${option.nome} ${option.cognome || ""}`
              }
              renderInput={(params) => (
                <TextField {...params} label="Risorsa" fullWidth />
              )}
              sx={{ mb: 2 }}
            />
            <Grid container spacing={2}>
              <Grid size={{ xs: 6 }}>
                <TextField
                  fullWidth
                  label="Ora Inizio"
                  type="time"
                  InputLabelProps={{ shrink: true }}
                />
              </Grid>
              <Grid size={{ xs: 6 }}>
                <TextField
                  fullWidth
                  label="Ora Fine"
                  type="time"
                  InputLabelProps={{ shrink: true }}
                />
              </Grid>
            </Grid>
            <TextField
              fullWidth
              label="Note"
              multiline
              rows={2}
              sx={{ mt: 2 }}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(null)}>Annulla</Button>
          <Button variant="contained">Aggiungi</Button>
        </DialogActions>
      </Dialog>

      {/* Dialog: Aggiungi Acconto */}
      <Dialog
        open={dialogOpen === "acconto"}
        onClose={() => setDialogOpen(null)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Aggiungi Acconto</DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2 }}>
            <TextField
              fullWidth
              label="Data"
              type="date"
              defaultValue={dayjs().format("YYYY-MM-DD")}
              InputLabelProps={{ shrink: true }}
              sx={{ mb: 2 }}
            />
            <TextField fullWidth label="Importo" type="number" sx={{ mb: 2 }} />
            <TextField fullWidth label="Descrizione" sx={{ mb: 2 }} />
            <FormControl fullWidth>
              <InputLabel>Metodo Pagamento</InputLabel>
              <Select label="Metodo Pagamento">
                <MenuItem value="contanti">Contanti</MenuItem>
                <MenuItem value="bonifico">Bonifico</MenuItem>
                <MenuItem value="carta">Carta</MenuItem>
                <MenuItem value="assegno">Assegno</MenuItem>
              </Select>
            </FormControl>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(null)}>Annulla</Button>
          <Button variant="contained">Aggiungi</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default EventoDetailPage;
