import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  Box,
  Paper,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Button,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  Divider,
  Chip,
  Switch,
  FormControlLabel,
  Card,
  CardContent,
  Alert,
  Tooltip,
} from '@mui/material';
import {
  Add as AddIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
  Refresh as RefreshIcon,
  CheckCircle as PaidIcon,
  Cancel as UnpaidIcon,
  DragIndicator as DragIcon,
} from '@mui/icons-material';
import dayjs from 'dayjs';
import {
  eventoCostiApi,
  eventoAltriCostiApi,
  eventoAccontiApi,
} from '../services/api';
import type {
  EventoAltroCosto,
  EventoAcconto,
  EventoCostiRiepilogo,
} from '../types';
import { formatCurrency } from '../types';

interface EventoCostiPanelProps {
  eventoId: number;
}

const EventoCostiPanel: React.FC<EventoCostiPanelProps> = ({ eventoId }) => {
  const queryClient = useQueryClient();

  // State for dialogs
  const [costoDialogOpen, setCostoDialogOpen] = useState(false);
  const [accontoDialogOpen, setAccontoDialogOpen] = useState(false);
  const [pagaDialogOpen, setPagaDialogOpen] = useState(false);
  const [editingCosto, setEditingCosto] = useState<EventoAltroCosto | null>(null);
  const [editingAcconto, setEditingAcconto] = useState<EventoAcconto | null>(null);
  const [costoForm, setCostoForm] = useState<Partial<EventoAltroCosto>>({
    quantita: 1,
    applicaIva: true,
    aliquotaIva: 10,
  });
  const [accontoForm, setAccontoForm] = useState<Partial<EventoAcconto>>({});
  const [pagaForm, setPagaForm] = useState<{ dataPagamento?: string; metodoPagamento?: string }>({});

  // Queries
  const { data: riepilogo, isLoading: riepilogoLoading } = useQuery({
    queryKey: ['eventoCosti', eventoId],
    queryFn: () => eventoCostiApi.getRiepilogo(eventoId),
  });

  const { data: altriCosti } = useQuery({
    queryKey: ['eventoAltriCosti', eventoId],
    queryFn: () => eventoAltriCostiApi.getByEventoId(eventoId),
  });

  const { data: acconti } = useQuery({
    queryKey: ['eventoAcconti', eventoId],
    queryFn: () => eventoAccontiApi.getByEventoId(eventoId),
  });

  // Mutations
  const ricalcolaAccontiMutation = useMutation({
    mutationFn: () => eventoCostiApi.ricalcolaAcconti(eventoId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventoCosti', eventoId] });
      queryClient.invalidateQueries({ queryKey: ['eventoAcconti', eventoId] });
    },
  });

  const saveCostoMutation = useMutation({
    mutationFn: (data: Partial<EventoAltroCosto>) =>
      editingCosto
        ? eventoAltriCostiApi.update(eventoId, editingCosto.id, data)
        : eventoAltriCostiApi.create(eventoId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventoAltriCosti', eventoId] });
      queryClient.invalidateQueries({ queryKey: ['eventoCosti', eventoId] });
      handleCloseCostoDialog();
    },
  });

  const deleteCostoMutation = useMutation({
    mutationFn: (id: number) => eventoAltriCostiApi.delete(eventoId, id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventoAltriCosti', eventoId] });
      queryClient.invalidateQueries({ queryKey: ['eventoCosti', eventoId] });
    },
  });

  const saveAccontoMutation = useMutation({
    mutationFn: (data: Partial<EventoAcconto>) =>
      editingAcconto
        ? eventoAccontiApi.update(eventoId, editingAcconto.id, data)
        : eventoAccontiApi.create(eventoId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventoAcconti', eventoId] });
      queryClient.invalidateQueries({ queryKey: ['eventoCosti', eventoId] });
      handleCloseAccontoDialog();
    },
  });

  const deleteAccontoMutation = useMutation({
    mutationFn: (id: number) => eventoAccontiApi.delete(eventoId, id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventoAcconti', eventoId] });
      queryClient.invalidateQueries({ queryKey: ['eventoCosti', eventoId] });
    },
  });

  const pagaAccontoMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: any }) =>
      eventoAccontiApi.paga(eventoId, id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventoAcconti', eventoId] });
      queryClient.invalidateQueries({ queryKey: ['eventoCosti', eventoId] });
      handleClosePagaDialog();
    },
  });

  // Handlers
  const handleOpenCostoDialog = (costo?: EventoAltroCosto) => {
    if (costo) {
      setEditingCosto(costo);
      setCostoForm(costo);
    } else {
      setEditingCosto(null);
      setCostoForm({ quantita: 1, applicaIva: true, aliquotaIva: 10 });
    }
    setCostoDialogOpen(true);
  };

  const handleCloseCostoDialog = () => {
    setCostoDialogOpen(false);
    setEditingCosto(null);
    setCostoForm({ quantita: 1, applicaIva: true, aliquotaIva: 10 });
  };

  const handleSaveCosto = () => {
    saveCostoMutation.mutate(costoForm);
  };

  const handleOpenAccontoDialog = (acconto?: EventoAcconto) => {
    if (acconto) {
      setEditingAcconto(acconto);
      setAccontoForm(acconto);
    } else {
      setEditingAcconto(null);
      setAccontoForm({});
    }
    setAccontoDialogOpen(true);
  };

  const handleCloseAccontoDialog = () => {
    setAccontoDialogOpen(false);
    setEditingAcconto(null);
    setAccontoForm({});
  };

  const handleSaveAcconto = () => {
    saveAccontoMutation.mutate(accontoForm);
  };

  const handleOpenPagaDialog = (acconto: EventoAcconto) => {
    setEditingAcconto(acconto);
    setPagaForm({ dataPagamento: dayjs().format('YYYY-MM-DD') });
    setPagaDialogOpen(true);
  };

  const handleClosePagaDialog = () => {
    setPagaDialogOpen(false);
    setEditingAcconto(null);
    setPagaForm({});
  };

  const handlePagaAcconto = () => {
    if (editingAcconto) {
      pagaAccontoMutation.mutate({ id: editingAcconto.id, data: pagaForm });
    }
  };

  // Calculate preview totals for form
  const calcolaTotale = () => {
    const costo = costoForm.costoUnitario || 0;
    const qta = costoForm.quantita || 1;
    const totale = costo * qta;
    const iva = costoForm.applicaIva ? totale * (costoForm.aliquotaIva || 10) / 100 : 0;
    return { totale, iva, totaleConIva: totale + iva };
  };

  return (
    <Box>
      {/* Riepilogo Costi */}
      <Card sx={{ mb: 3, backgroundColor: '#f8f9fa' }}>
        <CardContent>
          <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
            <Typography variant="h6" sx={{ color: '#1976d2' }}>
              Riepilogo Costi Evento
            </Typography>
            <Button
              variant="outlined"
              size="small"
              startIcon={<RefreshIcon />}
              onClick={() => ricalcolaAccontiMutation.mutate()}
              disabled={ricalcolaAccontiMutation.isPending}
            >
              Ricalcola Acconti
            </Button>
          </Box>

          {riepilogo && (
            <Grid container spacing={2}>
              <Grid size={{ xs: 12, md: 6 }}>
                <Box sx={{ p: 2, backgroundColor: 'white', borderRadius: 1 }}>
                  <Typography variant="subtitle2" color="textSecondary">Dettaglio Voci</Typography>
                  <Divider sx={{ my: 1 }} />
                  <Box display="flex" justifyContent="space-between" mb={0.5}>
                    <Typography variant="body2">Costo Ospiti:</Typography>
                    <Typography variant="body2">{formatCurrency(riepilogo.costoOspitiConIva)}</Typography>
                  </Box>
                  <Box display="flex" justifyContent="space-between" mb={0.5}>
                    <Typography variant="body2">Costo Risorse:</Typography>
                    <Typography variant="body2">{formatCurrency(riepilogo.costoRisorse)}</Typography>
                  </Box>
                  <Box display="flex" justifyContent="space-between" mb={0.5}>
                    <Typography variant="body2">Altri Costi:</Typography>
                    <Typography variant="body2">{formatCurrency(riepilogo.altriCostiConIva)}</Typography>
                  </Box>
                  <Box display="flex" justifyContent="space-between" mb={0.5} sx={{ color: 'error.main' }}>
                    <Typography variant="body2">Degustazioni (detraibile):</Typography>
                    <Typography variant="body2">- {formatCurrency(riepilogo.costoDegustazioni)}</Typography>
                  </Box>
                  <Divider sx={{ my: 1 }} />
                  <Box display="flex" justifyContent="space-between">
                    <Typography variant="subtitle1" fontWeight="bold">TOTALE EVENTO:</Typography>
                    <Typography variant="subtitle1" fontWeight="bold" color="primary">
                      {formatCurrency(riepilogo.costoTotale)}
                    </Typography>
                  </Box>
                </Box>
              </Grid>
              <Grid size={{ xs: 12, md: 6 }}>
                <Box sx={{ p: 2, backgroundColor: 'white', borderRadius: 1 }}>
                  <Typography variant="subtitle2" color="textSecondary">Situazione Pagamenti</Typography>
                  <Divider sx={{ my: 1 }} />
                  <Box display="flex" justifyContent="space-between" mb={0.5}>
                    <Typography variant="body2">Acconti Pagati:</Typography>
                    <Typography variant="body2" color="success.main">
                      {formatCurrency(riepilogo.totaleAccontiPagati)}
                    </Typography>
                  </Box>
                  <Box display="flex" justifyContent="space-between" mb={0.5}>
                    <Typography variant="body2">Acconti Previsti:</Typography>
                    <Typography variant="body2">{formatCurrency(riepilogo.totaleAccontiPrevisti)}</Typography>
                  </Box>
                  <Divider sx={{ my: 1 }} />
                  <Box display="flex" justifyContent="space-between">
                    <Typography variant="subtitle1" fontWeight="bold">SALDO DA PAGARE:</Typography>
                    <Typography variant="subtitle1" fontWeight="bold" color="error">
                      {formatCurrency(riepilogo.saldo)}
                    </Typography>
                  </Box>
                  <Divider sx={{ my: 1 }} />
                  <Box display="flex" justifyContent="space-between">
                    <Typography variant="body2">Costo per persona ({riepilogo.numeroOspiti} ospiti):</Typography>
                    <Typography variant="body2" fontWeight="bold">
                      {formatCurrency(riepilogo.costoPerPersona)}
                    </Typography>
                  </Box>
                </Box>
              </Grid>
            </Grid>
          )}
        </CardContent>
      </Card>

      {/* Altri Costi */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
          <Typography variant="h6">Altri Costi</Typography>
          <Button
            variant="contained"
            size="small"
            startIcon={<AddIcon />}
            onClick={() => handleOpenCostoDialog()}
          >
            Aggiungi Costo
          </Button>
        </Box>

        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ backgroundColor: '#e3f2fd' }}>
                <TableCell width={40}></TableCell>
                <TableCell>Descrizione</TableCell>
                <TableCell align="right">Costo Unit.</TableCell>
                <TableCell align="right">Qta</TableCell>
                <TableCell align="center">IVA</TableCell>
                <TableCell align="right">Totale</TableCell>
                <TableCell align="right">Totale + IVA</TableCell>
                <TableCell align="center" width={100}>Azioni</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {altriCosti?.map((costo) => (
                <TableRow key={costo.id} hover>
                  <TableCell>
                    <DragIcon sx={{ color: 'grey.400', cursor: 'grab' }} />
                  </TableCell>
                  <TableCell>{costo.descrizione}</TableCell>
                  <TableCell align="right">{formatCurrency(costo.costoUnitario)}</TableCell>
                  <TableCell align="right">{costo.quantita}</TableCell>
                  <TableCell align="center">
                    {costo.applicaIva ? (
                      <Chip label={`${costo.aliquotaIva}%`} size="small" color="primary" />
                    ) : (
                      <Chip label="No" size="small" />
                    )}
                  </TableCell>
                  <TableCell align="right">{formatCurrency(costo.totale)}</TableCell>
                  <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                    {formatCurrency(costo.totaleConIva)}
                  </TableCell>
                  <TableCell align="center">
                    <IconButton size="small" onClick={() => handleOpenCostoDialog(costo)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      color="error"
                      onClick={() => deleteCostoMutation.mutate(costo.id)}
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {(!altriCosti || altriCosti.length === 0) && (
                <TableRow>
                  <TableCell colSpan={8} align="center">
                    <Typography color="textSecondary">Nessun costo aggiuntivo</Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>

      {/* Acconti */}
      <Paper sx={{ p: 2 }}>
        <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
          <Typography variant="h6">Registro Acconti</Typography>
          <Button
            variant="contained"
            size="small"
            startIcon={<AddIcon />}
            onClick={() => handleOpenAccontoDialog()}
          >
            Aggiungi Acconto
          </Button>
        </Box>

        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ backgroundColor: '#e3f2fd' }}>
                <TableCell>Descrizione</TableCell>
                <TableCell align="right">Importo</TableCell>
                <TableCell align="center">A Conferma</TableCell>
                <TableCell align="center">Stato</TableCell>
                <TableCell>Data Pagamento</TableCell>
                <TableCell>Metodo</TableCell>
                <TableCell align="center" width={120}>Azioni</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {acconti?.map((acconto) => (
                <TableRow
                  key={acconto.id}
                  hover
                  sx={{
                    backgroundColor: acconto.pagato ? '#e8f5e9' : 'inherit',
                  }}
                >
                  <TableCell>{acconto.descrizione || '-'}</TableCell>
                  <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                    {formatCurrency(acconto.importo)}
                  </TableCell>
                  <TableCell align="center">
                    {acconto.aConferma && <Chip label="Si" size="small" color="warning" />}
                  </TableCell>
                  <TableCell align="center">
                    {acconto.pagato ? (
                      <Chip icon={<PaidIcon />} label="Pagato" size="small" color="success" />
                    ) : (
                      <Chip icon={<UnpaidIcon />} label="Da pagare" size="small" color="default" />
                    )}
                  </TableCell>
                  <TableCell>
                    {acconto.dataPagamento
                      ? dayjs(acconto.dataPagamento).format('DD/MM/YYYY')
                      : '-'}
                  </TableCell>
                  <TableCell>{acconto.metodoPagamento || '-'}</TableCell>
                  <TableCell align="center">
                    {!acconto.pagato && (
                      <Tooltip title="Segna come pagato">
                        <IconButton
                          size="small"
                          color="success"
                          onClick={() => handleOpenPagaDialog(acconto)}
                        >
                          <PaidIcon fontSize="small" />
                        </IconButton>
                      </Tooltip>
                    )}
                    <IconButton size="small" onClick={() => handleOpenAccontoDialog(acconto)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      color="error"
                      onClick={() => deleteAccontoMutation.mutate(acconto.id)}
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {(!acconti || acconti.length === 0) && (
                <TableRow>
                  <TableCell colSpan={7} align="center">
                    <Typography color="textSecondary">Nessun acconto registrato</Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>

      {/* Dialog: Aggiungi/Modifica Costo */}
      <Dialog open={costoDialogOpen} onClose={handleCloseCostoDialog} maxWidth="sm" fullWidth>
        <DialogTitle>{editingCosto ? 'Modifica Costo' : 'Nuovo Costo'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12 }}>
              <TextField
                fullWidth
                label="Descrizione"
                value={costoForm.descrizione || ''}
                onChange={(e) => setCostoForm({ ...costoForm, descrizione: e.target.value })}
                required
                multiline
                rows={2}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                label="Costo Unitario"
                type="number"
                value={costoForm.costoUnitario || ''}
                onChange={(e) => setCostoForm({ ...costoForm, costoUnitario: Number(e.target.value) })}
                required
                InputProps={{ inputProps: { step: 0.01 } }}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                label="Quantita"
                type="number"
                value={costoForm.quantita || 1}
                onChange={(e) => setCostoForm({ ...costoForm, quantita: Number(e.target.value) })}
                InputProps={{ inputProps: { min: 1 } }}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={costoForm.applicaIva ?? true}
                    onChange={(e) => setCostoForm({ ...costoForm, applicaIva: e.target.checked })}
                  />
                }
                label="Applica IVA"
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                label="Aliquota IVA %"
                type="number"
                value={costoForm.aliquotaIva || 10}
                onChange={(e) => setCostoForm({ ...costoForm, aliquotaIva: Number(e.target.value) })}
                disabled={!costoForm.applicaIva}
                InputProps={{ inputProps: { min: 0, max: 100 } }}
              />
            </Grid>
            <Grid size={{ xs: 12 }}>
              <Alert severity="info">
                <Box display="flex" justifyContent="space-between">
                  <span>Totale: {formatCurrency(calcolaTotale().totale)}</span>
                  <span>IVA: {formatCurrency(calcolaTotale().iva)}</span>
                  <strong>Totale con IVA: {formatCurrency(calcolaTotale().totaleConIva)}</strong>
                </Box>
              </Alert>
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseCostoDialog}>Annulla</Button>
          <Button
            variant="contained"
            onClick={handleSaveCosto}
            disabled={saveCostoMutation.isPending}
          >
            Salva
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog: Aggiungi/Modifica Acconto */}
      <Dialog open={accontoDialogOpen} onClose={handleCloseAccontoDialog} maxWidth="sm" fullWidth>
        <DialogTitle>{editingAcconto ? 'Modifica Acconto' : 'Nuovo Acconto'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12 }}>
              <TextField
                fullWidth
                label="Descrizione"
                value={accontoForm.descrizione || ''}
                onChange={(e) => setAccontoForm({ ...accontoForm, descrizione: e.target.value })}
                multiline
                rows={2}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <TextField
                fullWidth
                label="Importo"
                type="number"
                value={accontoForm.importo || ''}
                onChange={(e) => setAccontoForm({ ...accontoForm, importo: Number(e.target.value) })}
                required
                InputProps={{ inputProps: { step: 0.01 } }}
              />
            </Grid>
            <Grid size={{ xs: 12, sm: 6 }}>
              <FormControlLabel
                control={
                  <Switch
                    checked={accontoForm.aConferma ?? false}
                    onChange={(e) => setAccontoForm({ ...accontoForm, aConferma: e.target.checked })}
                  />
                }
                label="A Conferma Evento"
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseAccontoDialog}>Annulla</Button>
          <Button
            variant="contained"
            onClick={handleSaveAcconto}
            disabled={saveAccontoMutation.isPending}
          >
            Salva
          </Button>
        </DialogActions>
      </Dialog>

      {/* Dialog: Paga Acconto */}
      <Dialog open={pagaDialogOpen} onClose={handleClosePagaDialog} maxWidth="xs" fullWidth>
        <DialogTitle>Registra Pagamento</DialogTitle>
        <DialogContent>
          <Typography gutterBottom>
            Acconto: <strong>{formatCurrency(editingAcconto?.importo)}</strong>
          </Typography>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid size={{ xs: 12 }}>
              <TextField
                fullWidth
                label="Data Pagamento"
                type="date"
                value={pagaForm.dataPagamento || dayjs().format('YYYY-MM-DD')}
                onChange={(e) => setPagaForm({ ...pagaForm, dataPagamento: e.target.value })}
                InputLabelProps={{ shrink: true }}
              />
            </Grid>
            <Grid size={{ xs: 12 }}>
              <TextField
                fullWidth
                label="Metodo Pagamento"
                value={pagaForm.metodoPagamento || ''}
                onChange={(e) => setPagaForm({ ...pagaForm, metodoPagamento: e.target.value })}
                placeholder="Es: Bonifico, Contanti, Carta..."
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClosePagaDialog}>Annulla</Button>
          <Button
            variant="contained"
            color="success"
            onClick={handlePagaAcconto}
            disabled={pagaAccontoMutation.isPending}
          >
            Conferma Pagamento
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default EventoCostiPanel;
