import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Box,
  Typography,
  Paper,
  Grid,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControlLabel,
  Checkbox,
  Chip,
  Card,
  CardContent,
  Divider,
  Alert,
  Tooltip,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import {
  Add as AddIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
  Refresh as RefreshIcon,
  Payment as PaymentIcon,
  CheckCircle as CheckIcon,
  Cancel as CancelIcon,
} from "@mui/icons-material";
import dayjs from "dayjs";
import { costiService, formatCurrency } from "../services/costiService";
import {
  EventoAltroCostoDto,
  EventoAccontoDto,
  PagaAccontoDto,
} from "../types";

interface EventoCostiPanelProps {
  eventoId: number;
}

export default function EventoCostiPanel({ eventoId }: EventoCostiPanelProps) {
  const queryClient = useQueryClient();
  const [dialogOpen, setDialogOpen] = useState<string | null>(null);
  const [dialogData, setDialogData] = useState<any>({});
  const [editingId, setEditingId] = useState<number | null>(null);

  // Query per il riepilogo costi
  const {
    data: riepilogo,
    isLoading,
    error,
  } = useQuery({
    queryKey: ["evento-costi", eventoId],
    queryFn: () => costiService.getRiepilogo(eventoId),
    enabled: eventoId > 0,
  });

  // Mutations
  const ricalcolaAccontiMutation = useMutation({
    mutationFn: () => costiService.ricalcolaAcconti(eventoId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento-costi", eventoId] });
      queryClient.invalidateQueries({ queryKey: ["evento", eventoId] });
    },
  });

  const addAltroCostoMutation = useMutation({
    mutationFn: (data: EventoAltroCostoDto) =>
      costiService.addAltroCosto(eventoId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento-costi", eventoId] });
      setDialogOpen(null);
    },
  });

  const updateAltroCostoMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: EventoAltroCostoDto }) =>
      costiService.updateAltroCosto(eventoId, id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento-costi", eventoId] });
      setDialogOpen(null);
      setEditingId(null);
    },
  });

  const deleteAltroCostoMutation = useMutation({
    mutationFn: (id: number) => costiService.deleteAltroCosto(eventoId, id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento-costi", eventoId] });
    },
  });

  const addAccontoMutation = useMutation({
    mutationFn: (data: EventoAccontoDto) =>
      costiService.addAcconto(eventoId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento-costi", eventoId] });
      setDialogOpen(null);
    },
  });

  const updateAccontoMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: EventoAccontoDto }) =>
      costiService.updateAcconto(eventoId, id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento-costi", eventoId] });
      setDialogOpen(null);
      setEditingId(null);
    },
  });

  const pagaAccontoMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: PagaAccontoDto }) =>
      costiService.pagaAcconto(eventoId, id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento-costi", eventoId] });
      queryClient.invalidateQueries({ queryKey: ["evento", eventoId] });
      setDialogOpen(null);
    },
  });

  const deleteAccontoMutation = useMutation({
    mutationFn: (id: number) => costiService.deleteAcconto(eventoId, id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["evento-costi", eventoId] });
    },
  });

  if (isLoading) {
    return <Typography>Caricamento costi...</Typography>;
  }

  if (error) {
    return <Alert severity="error">Errore nel caricamento dei costi</Alert>;
  }

  const calcolaTotalePreview = () => {
    const costoUnitario = parseFloat(dialogData.costoUnitario) || 0;
    const quantita = parseFloat(dialogData.quantita) || 1;
    const totale = costoUnitario * quantita;
    const applicaIva = dialogData.applicaIva !== false;
    const aliquotaIva = parseFloat(dialogData.aliquotaIva) || 10;
    const totaleConIva = applicaIva ? totale * (1 + aliquotaIva / 100) : totale;
    return { totale, totaleConIva };
  };

  return (
    <Box>
      {/* Riepilogo Costi */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            mb: 2,
          }}
        >
          <Typography variant="h6">Riepilogo Costi</Typography>
          <Button
            startIcon={<RefreshIcon />}
            onClick={() => ricalcolaAccontiMutation.mutate()}
            disabled={ricalcolaAccontiMutation.isPending}
          >
            Ricalcola Acconti
          </Button>
        </Box>

        <Grid container spacing={2}>
          {/* Colonna sinistra - Dettaglio costi */}
          <Grid size={{ xs: 12, md: 6 }}>
            <Card variant="outlined">
              <CardContent>
                <Typography
                  variant="subtitle2"
                  color="textSecondary"
                  gutterBottom
                >
                  Dettaglio Costi
                </Typography>
                <Table size="small">
                  <TableBody>
                    <TableRow>
                      <TableCell>Costo Ospiti</TableCell>
                      <TableCell align="right">
                        {formatCurrency(riepilogo?.costoOspiti)}
                      </TableCell>
                    </TableRow>
                    <TableRow>
                      <TableCell sx={{ pl: 3, color: "text.secondary" }}>
                        + IVA 10%
                      </TableCell>
                      <TableCell align="right" sx={{ color: "text.secondary" }}>
                        {formatCurrency(
                          (riepilogo?.costoOspitiConIva || 0) -
                            (riepilogo?.costoOspiti || 0),
                        )}
                      </TableCell>
                    </TableRow>
                    <TableRow>
                      <TableCell>Costo Risorse</TableCell>
                      <TableCell align="right">
                        {formatCurrency(riepilogo?.costoRisorse)}
                      </TableCell>
                    </TableRow>
                    <TableRow>
                      <TableCell>Altri Costi</TableCell>
                      <TableCell align="right">
                        {formatCurrency(riepilogo?.altriCosti)}
                      </TableCell>
                    </TableRow>
                    <TableRow>
                      <TableCell sx={{ pl: 3, color: "text.secondary" }}>
                        + IVA
                      </TableCell>
                      <TableCell align="right" sx={{ color: "text.secondary" }}>
                        {formatCurrency(
                          (riepilogo?.altriCostiConIva || 0) -
                            (riepilogo?.altriCosti || 0),
                        )}
                      </TableCell>
                    </TableRow>
                    {(riepilogo?.costoDegustazioni || 0) > 0 && (
                      <TableRow>
                        <TableCell sx={{ color: "success.main" }}>
                          - Degustazioni (detraibili)
                        </TableCell>
                        <TableCell align="right" sx={{ color: "success.main" }}>
                          {formatCurrency(riepilogo?.costoDegustazioni)}
                        </TableCell>
                      </TableRow>
                    )}
                    <TableRow
                      sx={{ "& td": { fontWeight: "bold", borderTop: 2 } }}
                    >
                      <TableCell>TOTALE LORDO</TableCell>
                      <TableCell align="right">
                        {formatCurrency(riepilogo?.totaleLordo)}
                      </TableCell>
                    </TableRow>
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </Grid>

          {/* Colonna destra - Totali e saldo */}
          <Grid size={{ xs: 12, md: 6 }}>
            <Card variant="outlined" sx={{ height: "100%" }}>
              <CardContent>
                <Typography
                  variant="subtitle2"
                  color="textSecondary"
                  gutterBottom
                >
                  Riepilogo Finale
                </Typography>
                <Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
                  <Box
                    sx={{ display: "flex", justifyContent: "space-between" }}
                  >
                    <Typography>N. Ospiti:</Typography>
                    <Typography fontWeight="bold">
                      {riepilogo?.numeroOspiti || 0}
                    </Typography>
                  </Box>
                  <Box
                    sx={{ display: "flex", justifyContent: "space-between" }}
                  >
                    <Typography>Costo per Persona:</Typography>
                    <Typography fontWeight="bold">
                      {formatCurrency(riepilogo?.costoPerPersona)}
                    </Typography>
                  </Box>
                  <Divider sx={{ my: 1 }} />
                  <Box
                    sx={{ display: "flex", justifyContent: "space-between" }}
                  >
                    <Typography variant="h6">TOTALE EVENTO:</Typography>
                    <Typography variant="h6" color="primary">
                      {formatCurrency(riepilogo?.costoTotale)}
                    </Typography>
                  </Box>
                  <Box
                    sx={{ display: "flex", justifyContent: "space-between" }}
                  >
                    <Typography>Acconti Pagati:</Typography>
                    <Typography color="success.main" fontWeight="bold">
                      {formatCurrency(riepilogo?.totaleAccontiPagati)}
                    </Typography>
                  </Box>
                  <Box
                    sx={{ display: "flex", justifyContent: "space-between" }}
                  >
                    <Typography variant="h6">SALDO:</Typography>
                    <Typography
                      variant="h6"
                      color={
                        (riepilogo?.saldo || 0) > 0
                          ? "error.main"
                          : "success.main"
                      }
                      fontWeight="bold"
                    >
                      {formatCurrency(riepilogo?.saldo)}
                    </Typography>
                  </Box>
                </Box>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Paper>

      {/* Altri Costi */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            mb: 2,
          }}
        >
          <Typography variant="h6">Altri Costi</Typography>
          <Button
            startIcon={<AddIcon />}
            variant="contained"
            size="small"
            onClick={() => {
              setDialogData({ quantita: 1, applicaIva: true, aliquotaIva: 10 });
              setEditingId(null);
              setDialogOpen("altroCosto");
            }}
          >
            Aggiungi Costo
          </Button>
        </Box>

        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ backgroundColor: "grey.100" }}>
                <TableCell>
                  <strong>Descrizione</strong>
                </TableCell>
                <TableCell align="right">
                  <strong>Costo Unit.</strong>
                </TableCell>
                <TableCell align="right">
                  <strong>Qta</strong>
                </TableCell>
                <TableCell align="right">
                  <strong>Totale</strong>
                </TableCell>
                <TableCell align="center">
                  <strong>IVA</strong>
                </TableCell>
                <TableCell align="right">
                  <strong>Totale c/IVA</strong>
                </TableCell>
                <TableCell width={100}></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {riepilogo?.dettaglioAltriCosti?.map((costo) => (
                <TableRow key={costo.id} hover>
                  <TableCell>{costo.descrizione}</TableCell>
                  <TableCell align="right">
                    {formatCurrency(costo.costoUnitario)}
                  </TableCell>
                  <TableCell align="right">{costo.quantita}</TableCell>
                  <TableCell align="right">
                    {formatCurrency(costo.totale)}
                  </TableCell>
                  <TableCell align="center">
                    {costo.applicaIva ? (
                      <Chip
                        label={`${costo.aliquotaIva}%`}
                        size="small"
                        color="info"
                      />
                    ) : (
                      <Chip label="No" size="small" variant="outlined" />
                    )}
                  </TableCell>
                  <TableCell align="right">
                    <strong>{formatCurrency(costo.totaleConIva)}</strong>
                  </TableCell>
                  <TableCell>
                    <IconButton
                      size="small"
                      onClick={() => {
                        setDialogData({
                          descrizione: costo.descrizione,
                          costoUnitario: costo.costoUnitario,
                          quantita: costo.quantita,
                          applicaIva: costo.applicaIva,
                          aliquotaIva: costo.aliquotaIva,
                        });
                        setEditingId(costo.id);
                        setDialogOpen("altroCosto");
                      }}
                    >
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      color="error"
                      onClick={() => deleteAltroCostoMutation.mutate(costo.id)}
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {(!riepilogo?.dettaglioAltriCosti ||
                riepilogo.dettaglioAltriCosti.length === 0) && (
                <TableRow>
                  <TableCell
                    colSpan={7}
                    align="center"
                    sx={{ py: 4, color: "text.secondary" }}
                  >
                    Nessun costo aggiuntivo. Clicca "Aggiungi Costo" per
                    aggiungerne uno.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>

      {/* Acconti */}
      <Paper sx={{ p: 2 }}>
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            mb: 2,
          }}
        >
          <Typography variant="h6">Acconti e Pagamenti</Typography>
          <Button
            startIcon={<AddIcon />}
            variant="contained"
            size="small"
            onClick={() => {
              setDialogData({ aConferma: false });
              setEditingId(null);
              setDialogOpen("acconto");
            }}
          >
            Aggiungi Acconto
          </Button>
        </Box>

        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ backgroundColor: "grey.100" }}>
                <TableCell width={50}>
                  <strong>#</strong>
                </TableCell>
                <TableCell>
                  <strong>Descrizione</strong>
                </TableCell>
                <TableCell align="right">
                  <strong>Importo</strong>
                </TableCell>
                <TableCell align="center">
                  <strong>Stato</strong>
                </TableCell>
                <TableCell>
                  <strong>Data Pag.</strong>
                </TableCell>
                <TableCell>
                  <strong>Metodo</strong>
                </TableCell>
                <TableCell width={150}></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {riepilogo?.dettaglioAcconti?.map((acconto) => (
                <TableRow key={acconto.id} hover>
                  <TableCell>
                    {acconto.aConferma ? (
                      <Tooltip title="A conferma evento">
                        <Chip label="C" size="small" color="warning" />
                      </Tooltip>
                    ) : (
                      <Typography variant="body2" color="textSecondary">
                        {acconto.ordine / 10}
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {acconto.descrizione}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">
                    <strong>{formatCurrency(acconto.importo)}</strong>
                  </TableCell>
                  <TableCell align="center">
                    {acconto.pagato ? (
                      <Chip
                        icon={<CheckIcon />}
                        label="Pagato"
                        size="small"
                        color="success"
                      />
                    ) : (
                      <Chip
                        icon={<CancelIcon />}
                        label="Da pagare"
                        size="small"
                        color="warning"
                        variant="outlined"
                      />
                    )}
                  </TableCell>
                  <TableCell>
                    {acconto.dataPagamento
                      ? dayjs(acconto.dataPagamento).format("DD/MM/YYYY")
                      : "-"}
                  </TableCell>
                  <TableCell>{acconto.pagato ? "Bonifico" : "-"}</TableCell>
                  <TableCell>
                    {!acconto.pagato && (
                      <Tooltip title="Segna come pagato">
                        <IconButton
                          size="small"
                          color="success"
                          onClick={() => {
                            setDialogData({
                              id: acconto.id,
                              dataPagamento: dayjs().format("YYYY-MM-DD"),
                              metodoPagamento: "Bonifico",
                            });
                            setDialogOpen("pagamento");
                          }}
                        >
                          <PaymentIcon fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                    <IconButton
                      size="small"
                      onClick={() => {
                        setDialogData({
                          descrizione: acconto.descrizione,
                          importo: acconto.importo,
                          aConferma: acconto.aConferma,
                        });
                        setEditingId(acconto.id);
                        setDialogOpen("acconto");
                      }}
                    >
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      color="error"
                      onClick={() => deleteAccontoMutation.mutate(acconto.id)}
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {(!riepilogo?.dettaglioAcconti ||
                riepilogo.dettaglioAcconti.length === 0) && (
                <TableRow>
                  <TableCell
                    colSpan={7}
                    align="center"
                    sx={{ py: 4, color: "text.secondary" }}
                  >
                    Nessun acconto registrato. Clicca "Ricalcola Acconti" per
                    generare gli acconti standard oppure "Aggiungi Acconto" per
                    inserirne uno manualmente.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>

      {/* Dialog Altro Costo */}
      <Dialog
        open={dialogOpen === "altroCosto"}
        onClose={() => setDialogOpen(null)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          {editingId ? "Modifica Costo" : "Aggiungi Costo"}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2, mt: 1 }}>
            <TextField
              label="Descrizione"
              fullWidth
              required
              value={dialogData.descrizione || ""}
              onChange={(e) =>
                setDialogData({ ...dialogData, descrizione: e.target.value })
              }
            />
            <Grid container spacing={2}>
              <Grid size={{ xs: 6 }}>
                <TextField
                  label="Costo Unitario"
                  type="number"
                  fullWidth
                  required
                  value={dialogData.costoUnitario || ""}
                  onChange={(e) =>
                    setDialogData({
                      ...dialogData,
                      costoUnitario: parseFloat(e.target.value),
                    })
                  }
                  InputProps={{
                    startAdornment: <Typography sx={{ mr: 0.5 }}>€</Typography>,
                  }}
                />
              </Grid>
              <Grid size={{ xs: 6 }}>
                <TextField
                  label="Quantità"
                  type="number"
                  fullWidth
                  value={dialogData.quantita || 1}
                  onChange={(e) =>
                    setDialogData({
                      ...dialogData,
                      quantita: parseFloat(e.target.value),
                    })
                  }
                />
              </Grid>
            </Grid>
            <Grid container spacing={2} alignItems="center">
              <Grid size={{ xs: 6 }}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={dialogData.applicaIva !== false}
                      onChange={(e) =>
                        setDialogData({
                          ...dialogData,
                          applicaIva: e.target.checked,
                        })
                      }
                    />
                  }
                  label="Applica IVA"
                />
              </Grid>
              <Grid size={{ xs: 6 }}>
                <TextField
                  label="Aliquota IVA %"
                  type="number"
                  fullWidth
                  disabled={dialogData.applicaIva === false}
                  value={dialogData.aliquotaIva || 10}
                  onChange={(e) =>
                    setDialogData({
                      ...dialogData,
                      aliquotaIva: parseFloat(e.target.value),
                    })
                  }
                />
              </Grid>
            </Grid>

            {/* Preview calcolo */}
            <Card variant="outlined" sx={{ bgcolor: "grey.50" }}>
              <CardContent sx={{ py: 1 }}>
                <Box sx={{ display: "flex", justifyContent: "space-between" }}>
                  <Typography variant="body2">Totale:</Typography>
                  <Typography variant="body2">
                    {formatCurrency(calcolaTotalePreview().totale)}
                  </Typography>
                </Box>
                <Box sx={{ display: "flex", justifyContent: "space-between" }}>
                  <Typography variant="body2" fontWeight="bold">
                    Totale con IVA:
                  </Typography>
                  <Typography variant="body2" fontWeight="bold">
                    {formatCurrency(calcolaTotalePreview().totaleConIva)}
                  </Typography>
                </Box>
              </CardContent>
            </Card>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(null)}>Annulla</Button>
          <Button
            variant="contained"
            onClick={() => {
              const data: EventoAltroCostoDto = {
                descrizione: dialogData.descrizione,
                costoUnitario: dialogData.costoUnitario,
                quantita: dialogData.quantita,
                applicaIva: dialogData.applicaIva,
                aliquotaIva: dialogData.aliquotaIva,
              };
              if (editingId) {
                updateAltroCostoMutation.mutate({ id: editingId, data });
              } else {
                addAltroCostoMutation.mutate(data);
              }
            }}
          >
            {editingId ? "Salva" : "Aggiungi"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Acconto */}
      <Dialog
        open={dialogOpen === "acconto"}
        onClose={() => setDialogOpen(null)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          {editingId ? "Modifica Acconto" : "Aggiungi Acconto"}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2, mt: 1 }}>
            <TextField
              label="Descrizione"
              fullWidth
              value={dialogData.descrizione || ""}
              onChange={(e) =>
                setDialogData({ ...dialogData, descrizione: e.target.value })
              }
            />
            <TextField
              label="Importo"
              type="number"
              fullWidth
              required
              value={dialogData.importo || ""}
              onChange={(e) =>
                setDialogData({
                  ...dialogData,
                  importo: parseFloat(e.target.value),
                })
              }
              InputProps={{
                startAdornment: <Typography sx={{ mr: 0.5 }}>€</Typography>,
              }}
            />
            <FormControlLabel
              control={
                <Checkbox
                  checked={dialogData.aConferma || false}
                  onChange={(e) =>
                    setDialogData({
                      ...dialogData,
                      aConferma: e.target.checked,
                    })
                  }
                />
              }
              label="A conferma evento"
            />
            <TextField
              label="Note"
              fullWidth
              multiline
              rows={2}
              value={dialogData.note || ""}
              onChange={(e) =>
                setDialogData({ ...dialogData, note: e.target.value })
              }
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(null)}>Annulla</Button>
          <Button
            variant="contained"
            onClick={() => {
              const data: EventoAccontoDto = {
                descrizione: dialogData.descrizione,
                importo: dialogData.importo,
                aConferma: dialogData.aConferma,
                note: dialogData.note,
              };
              if (editingId) {
                updateAccontoMutation.mutate({ id: editingId, data });
              } else {
                addAccontoMutation.mutate(data);
              }
            }}
          >
            {editingId ? "Salva" : "Aggiungi"}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog Pagamento */}
      <Dialog
        open={dialogOpen === "pagamento"}
        onClose={() => setDialogOpen(null)}
        maxWidth="xs"
        fullWidth
      >
        <DialogTitle>Registra Pagamento</DialogTitle>
        <DialogContent>
          <Box sx={{ display: "flex", flexDirection: "column", gap: 2, mt: 1 }}>
            <DatePicker
              label="Data Pagamento"
              value={
                dialogData.dataPagamento
                  ? dayjs(dialogData.dataPagamento)
                  : null
              }
              onChange={(date) =>
                setDialogData({
                  ...dialogData,
                  dataPagamento: date?.format("YYYY-MM-DD"),
                })
              }
              slotProps={{ textField: { fullWidth: true } }}
            />
            <FormControl fullWidth>
              <InputLabel>Metodo Pagamento</InputLabel>
              <Select
                value={dialogData.metodoPagamento || ""}
                label="Metodo Pagamento"
                onChange={(e) =>
                  setDialogData({
                    ...dialogData,
                    metodoPagamento: e.target.value,
                  })
                }
              >
                <MenuItem value="Contanti">Contanti</MenuItem>
                <MenuItem value="Bonifico">Bonifico</MenuItem>
                <MenuItem value="Carta">Carta di Credito</MenuItem>
                <MenuItem value="Assegno">Assegno</MenuItem>
              </Select>
            </FormControl>
            <TextField
              label="Note"
              fullWidth
              multiline
              rows={2}
              value={dialogData.note || ""}
              onChange={(e) =>
                setDialogData({ ...dialogData, note: e.target.value })
              }
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(null)}>Annulla</Button>
          <Button
            variant="contained"
            color="success"
            onClick={() => {
              const data: PagaAccontoDto = {
                dataPagamento: dialogData.dataPagamento,
                metodoPagamento: dialogData.metodoPagamento,
                note: dialogData.note,
              };
              pagaAccontoMutation.mutate({ id: dialogData.id, data });
            }}
          >
            Conferma Pagamento
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
