import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  CardContent,
  Grid,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  IconButton,
  CircularProgress,
} from '@mui/material';
import {
  Event as EventIcon,
  People as PeopleIcon,
  LocationOn as LocationIcon,
  Inventory as InventoryIcon,
  Visibility as ViewIcon,
} from '@mui/icons-material';
import dayjs from 'dayjs';
import { eventiApi, clientiApi, locationApi, articoliApi } from '../services/api';
import { StatoEvento, getStatoLabel, getStatoColor, getStatoTextColor } from '../types';

const Dashboard: React.FC = () => {
  const navigate = useNavigate();

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

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

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

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

  // Filtra eventi futuri e prossimi
  const oggi = dayjs();
  const eventiProssimi = eventi
    ?.filter((e) => dayjs(e.dataEvento).isAfter(oggi.subtract(1, 'day')))
    .sort((a, b) => dayjs(a.dataEvento).unix() - dayjs(b.dataEvento).unix())
    .slice(0, 10);

  // Conta eventi per stato
  const eventiPerStato = {
    schede: eventi?.filter((e) => e.stato === StatoEvento.Scheda).length || 0,
    preventivi: eventi?.filter((e) => e.stato === StatoEvento.Preventivo).length || 0,
    confermati: eventi?.filter((e) => e.stato === StatoEvento.Confermato).length || 0,
  };

  const stats = [
    {
      title: 'Eventi Totali',
      value: eventi?.length || 0,
      icon: <EventIcon sx={{ fontSize: 40 }} />,
      color: '#1976d2',
    },
    {
      title: 'Clienti',
      value: clienti?.length || 0,
      icon: <PeopleIcon sx={{ fontSize: 40 }} />,
      color: '#2e7d32',
    },
    {
      title: 'Location',
      value: location?.length || 0,
      icon: <LocationIcon sx={{ fontSize: 40 }} />,
      color: '#ed6c02',
    },
    {
      title: 'Articoli',
      value: articoli?.length || 0,
      icon: <InventoryIcon sx={{ fontSize: 40 }} />,
      color: '#9c27b0',
    },
  ];

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

  return (
    <Box>
      <Typography variant="h4" gutterBottom sx={{ mb: 3 }}>
        Dashboard
      </Typography>

      {/* Stats Cards */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        {stats.map((stat) => (
          <Grid size={{ xs: 12, sm: 6, md: 3 }} key={stat.title}>
            <Card
              sx={{
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                borderLeft: `4px solid ${stat.color}`,
              }}
            >
              <CardContent sx={{ display: 'flex', alignItems: 'center', width: '100%' }}>
                <Box sx={{ color: stat.color, mr: 2 }}>{stat.icon}</Box>
                <Box>
                  <Typography color="textSecondary" variant="body2">
                    {stat.title}
                  </Typography>
                  <Typography variant="h4" component="div">
                    {stat.value}
                  </Typography>
                </Box>
              </CardContent>
            </Card>
          </Grid>
        ))}
      </Grid>

      {/* Eventi per Stato */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid size={{ xs: 12, md: 4 }}>
          <Card sx={{ backgroundColor: getStatoColor(StatoEvento.Scheda) }}>
            <CardContent>
              <Typography variant="h6" sx={{ color: getStatoTextColor(StatoEvento.Scheda) }}>
                Schede
              </Typography>
              <Typography variant="h3" sx={{ color: getStatoTextColor(StatoEvento.Scheda) }}>
                {eventiPerStato.schede}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, md: 4 }}>
          <Card sx={{ backgroundColor: getStatoColor(StatoEvento.Preventivo) }}>
            <CardContent>
              <Typography variant="h6" sx={{ color: getStatoTextColor(StatoEvento.Preventivo) }}>
                Preventivi
              </Typography>
              <Typography variant="h3" sx={{ color: getStatoTextColor(StatoEvento.Preventivo) }}>
                {eventiPerStato.preventivi}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, md: 4 }}>
          <Card sx={{ backgroundColor: getStatoColor(StatoEvento.Confermato) }}>
            <CardContent>
              <Typography variant="h6" sx={{ color: getStatoTextColor(StatoEvento.Confermato) }}>
                Confermati
              </Typography>
              <Typography variant="h3" sx={{ color: getStatoTextColor(StatoEvento.Confermato) }}>
                {eventiPerStato.confermati}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Prossimi Eventi */}
      <Paper sx={{ p: 2 }}>
        <Typography variant="h6" gutterBottom>
          Prossimi Eventi
        </Typography>
        <TableContainer>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ backgroundColor: '#f5f5f5' }}>
                <TableCell>Data</TableCell>
                <TableCell>Descrizione</TableCell>
                <TableCell>Cliente</TableCell>
                <TableCell>Location</TableCell>
                <TableCell>Ospiti</TableCell>
                <TableCell>Stato</TableCell>
                <TableCell align="center">Azioni</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {eventiProssimi?.map((evento) => (
                <TableRow
                  key={evento.id}
                  hover
                  sx={{
                    backgroundColor: getStatoColor(evento.stato),
                    '&:hover': {
                      backgroundColor: getStatoColor(evento.stato),
                      filter: 'brightness(0.95)',
                    },
                  }}
                >
                  <TableCell>
                    <Typography variant="body2" fontWeight="bold">
                      {dayjs(evento.dataEvento).format('DD/MM/YYYY')}
                    </Typography>
                    {evento.oraInizio && (
                      <Typography variant="caption" color="textSecondary">
                        {evento.oraInizio}
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell>{evento.descrizione || '-'}</TableCell>
                  <TableCell>{evento.cliente?.ragioneSociale || '-'}</TableCell>
                  <TableCell>{evento.location?.nome || '-'}</TableCell>
                  <TableCell align="center">{evento.numeroOspiti || '-'}</TableCell>
                  <TableCell>
                    <Chip
                      label={getStatoLabel(evento.stato)}
                      size="small"
                      sx={{
                        backgroundColor: getStatoTextColor(evento.stato),
                        color: 'white',
                      }}
                    />
                  </TableCell>
                  <TableCell align="center">
                    <IconButton
                      size="small"
                      onClick={() => navigate(`/eventi/${evento.id}`)}
                      title="Visualizza"
                    >
                      <ViewIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
              {(!eventiProssimi || eventiProssimi.length === 0) && (
                <TableRow>
                  <TableCell colSpan={7} align="center">
                    <Typography color="textSecondary">Nessun evento prossimo</Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>
    </Box>
  );
};

export default Dashboard;
