import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Button,
  Paper,
  Chip,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
} from '@mui/material';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { DatePicker } from '@mui/x-date-pickers';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  ContentCopy as CopyIcon,
  Visibility as ViewIcon,
} from '@mui/icons-material';
import dayjs from 'dayjs';
import { eventiService } from '../services/eventiService';
import { lookupService } from '../services/lookupService';
import { Evento, StatoEvento } from '../types';

const getStatoLabel = (stato: StatoEvento) => {
  switch (stato) {
    case StatoEvento.Scheda: return 'Scheda';
    case StatoEvento.Preventivo: return 'Preventivo';
    case StatoEvento.Confermato: return 'Confermato';
    default: return 'Sconosciuto';
  }
};

const getStatoColor = (stato: StatoEvento): 'default' | 'warning' | 'success' => {
  switch (stato) {
    case StatoEvento.Scheda: return 'default';
    case StatoEvento.Preventivo: return 'warning';
    case StatoEvento.Confermato: return 'success';
    default: return 'default';
  }
};

export default function EventiPage() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [openDialog, setOpenDialog] = useState(false);
  const [formData, setFormData] = useState<Partial<Evento>>({
    dataEvento: dayjs().format('YYYY-MM-DD'),
    stato: StatoEvento.Scheda,
  });

  const { data: eventi = [], isLoading } = useQuery({
    queryKey: ['eventi'],
    queryFn: () => eventiService.getAll(),
  });

  const { data: clienti = [] } = useQuery({
    queryKey: ['lookup', 'clienti'],
    queryFn: () => lookupService.getClienti(),
  });

  const { data: locations = [] } = useQuery({
    queryKey: ['lookup', 'location'],
    queryFn: () => lookupService.getLocation(),
  });

  const { data: tipiEvento = [] } = useQuery({
    queryKey: ['lookup', 'tipi-evento'],
    queryFn: () => lookupService.getTipiEvento(),
  });

  const createMutation = useMutation({
    mutationFn: (data: Partial<Evento>) => eventiService.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventi'] });
      setOpenDialog(false);
      setFormData({ dataEvento: dayjs().format('YYYY-MM-DD'), stato: StatoEvento.Scheda });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => eventiService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventi'] });
    },
  });

  const duplicaMutation = useMutation({
    mutationFn: (id: number) => eventiService.duplica(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['eventi'] });
    },
  });

  const columns: GridColDef[] = [
    { field: 'codice', headerName: 'Codice', width: 120 },
    {
      field: 'dataEvento',
      headerName: 'Data',
      width: 120,
      valueFormatter: (value: string) => dayjs(value).format('DD/MM/YYYY'),
    },
    { field: 'descrizione', headerName: 'Descrizione', flex: 1, minWidth: 200 },
    {
      field: 'cliente',
      headerName: 'Cliente',
      width: 180,
      valueGetter: (value: any) => value?.ragioneSociale || '',
    },
    {
      field: 'location',
      headerName: 'Location',
      width: 150,
      valueGetter: (value: any) => value?.nome || '',
    },
    {
      field: 'numeroOspiti',
      headerName: 'Ospiti',
      width: 80,
      align: 'center',
    },
    {
      field: 'stato',
      headerName: 'Stato',
      width: 120,
      renderCell: (params) => (
        <Chip
          label={getStatoLabel(params.value)}
          color={getStatoColor(params.value)}
          size="small"
        />
      ),
    },
    {
      field: 'actions',
      headerName: 'Azioni',
      width: 180,
      sortable: false,
      renderCell: (params) => (
        <Box>
          <IconButton size="small" onClick={() => navigate(`/eventi/${params.row.id}`)}>
            <ViewIcon />
          </IconButton>
          <IconButton size="small" onClick={() => navigate(`/eventi/${params.row.id}`)}>
            <EditIcon />
          </IconButton>
          <IconButton size="small" onClick={() => duplicaMutation.mutate(params.row.id)}>
            <CopyIcon />
          </IconButton>
          <IconButton
            size="small"
            color="error"
            onClick={() => {
              if (confirm('Eliminare questo evento?')) {
                deleteMutation.mutate(params.row.id);
              }
            }}
          >
            <DeleteIcon />
          </IconButton>
        </Box>
      ),
    },
  ];

  const handleSubmit = () => {
    createMutation.mutate(formData);
  };

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h4">Eventi</Typography>
        <Button variant="contained" startIcon={<AddIcon />} onClick={() => setOpenDialog(true)}>
          Nuovo Evento
        </Button>
      </Box>

      <Paper sx={{ height: 600, width: '100%' }}>
        <DataGrid
          rows={eventi}
          columns={columns}
          loading={isLoading}
          pageSizeOptions={[10, 25, 50]}
          initialState={{
            pagination: { paginationModel: { pageSize: 25 } },
            sorting: { sortModel: [{ field: 'dataEvento', sort: 'asc' }] },
          }}
          disableRowSelectionOnClick
        />
      </Paper>

      <Dialog open={openDialog} onClose={() => setOpenDialog(false)} maxWidth="sm" fullWidth>
        <DialogTitle>Nuovo Evento</DialogTitle>
        <DialogContent>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 1 }}>
            <DatePicker
              label="Data Evento"
              value={formData.dataEvento ? dayjs(formData.dataEvento) : null}
              onChange={(date) => setFormData({ ...formData, dataEvento: date?.format('YYYY-MM-DD') })}
              slotProps={{ textField: { fullWidth: true } }}
            />
            <TextField
              label="Descrizione"
              fullWidth
              value={formData.descrizione || ''}
              onChange={(e) => setFormData({ ...formData, descrizione: e.target.value })}
            />
            <FormControl fullWidth>
              <InputLabel>Cliente</InputLabel>
              <Select
                value={formData.clienteId || ''}
                label="Cliente"
                onChange={(e) => setFormData({ ...formData, clienteId: e.target.value as number })}
              >
                {clienti.map((c) => (
                  <MenuItem key={c.id} value={c.id}>{c.ragioneSociale}</MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl fullWidth>
              <InputLabel>Location</InputLabel>
              <Select
                value={formData.locationId || ''}
                label="Location"
                onChange={(e) => setFormData({ ...formData, locationId: e.target.value as number })}
              >
                {locations.map((l) => (
                  <MenuItem key={l.id} value={l.id}>{l.nome}</MenuItem>
                ))}
              </Select>
            </FormControl>
            <FormControl fullWidth>
              <InputLabel>Tipo Evento</InputLabel>
              <Select
                value={formData.tipoEventoId || ''}
                label="Tipo Evento"
                onChange={(e) => setFormData({ ...formData, tipoEventoId: e.target.value as number })}
              >
                {tipiEvento.map((t) => (
                  <MenuItem key={t.id} value={t.id}>{t.descrizione}</MenuItem>
                ))}
              </Select>
            </FormControl>
            <TextField
              label="Numero Ospiti"
              type="number"
              fullWidth
              value={formData.numeroOspiti || ''}
              onChange={(e) => setFormData({ ...formData, numeroOspiti: parseInt(e.target.value) || undefined })}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDialog(false)}>Annulla</Button>
          <Button variant="contained" onClick={handleSubmit}>Crea</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
