import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Grid,
  Paper,
  Typography,
  Box,
  Card,
  CardContent,
  List,
  ListItem,
  ListItemText,
  Chip,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Alert,
  CircularProgress,
} from "@mui/material";
import {
  Event as EventIcon,
  People as PeopleIcon,
  CheckCircle as ConfirmedIcon,
  PendingActions as PendingIcon,
  PlayArrow as GenerateIcon,
  DeleteSweep as ClearIcon,
} from "@mui/icons-material";
import { useNavigate } from "react-router-dom";
import dayjs from "dayjs";
import { eventiService } from "../services/eventiService";
import { demoService, DemoDataResult } from "../services/demoService";
import { StatoEvento } from "../types";

const StatCard = ({
  title,
  value,
  icon,
  color,
}: {
  title: string;
  value: number;
  icon: React.ReactNode;
  color: string;
}) => (
  <Card sx={{ height: "100%" }}>
    <CardContent>
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        }}
      >
        <Box>
          <Typography color="textSecondary" gutterBottom variant="body2">
            {title}
          </Typography>
          <Typography variant="h4">{value}</Typography>
        </Box>
        <Box sx={{ color, opacity: 0.7 }}>{icon}</Box>
      </Box>
    </CardContent>
  </Card>
);

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) => {
  switch (stato) {
    case StatoEvento.Scheda:
      return "default";
    case StatoEvento.Preventivo:
      return "warning";
    case StatoEvento.Confermato:
      return "success";
    default:
      return "default";
  }
};

export default function Dashboard() {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [demoDialog, setDemoDialog] = useState<"generate" | "clear" | null>(
    null,
  );
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<DemoDataResult | null>(null);
  const [error, setError] = useState<string | null>(null);

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

  const handleGenerateDemo = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await demoService.generateDemoData();
      setResult(res);
      queryClient.invalidateQueries();
    } catch (err: any) {
      setError(
        err.response?.data?.error || "Errore durante la generazione dei dati",
      );
    } finally {
      setLoading(false);
    }
  };

  const handleClearDemo = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await demoService.clearDemoData();
      setResult(res);
      queryClient.invalidateQueries();
    } catch (err: any) {
      setError(
        err.response?.data?.error || "Errore durante la pulizia dei dati",
      );
    } finally {
      setLoading(false);
    }
  };

  const handleCloseDialog = () => {
    setDemoDialog(null);
    setResult(null);
    setError(null);
  };

  const oggi = dayjs().startOf("day");
  const prossimi30Giorni = oggi.add(30, "day");

  const eventiProssimi = eventi
    .filter(
      (e) =>
        dayjs(e.dataEvento).isAfter(oggi) &&
        dayjs(e.dataEvento).isBefore(prossimi30Giorni),
    )
    .sort((a, b) => dayjs(a.dataEvento).diff(dayjs(b.dataEvento)));

  const eventiConfermati = eventi.filter(
    (e) => e.stato === StatoEvento.Confermato,
  ).length;
  const eventiPreventivo = eventi.filter(
    (e) => e.stato === StatoEvento.Preventivo,
  ).length;
  const eventiOggi = eventi.filter((e) =>
    dayjs(e.dataEvento).isSame(oggi, "day"),
  ).length;

  return (
    <Box>
      <Box
        sx={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          mb: 3,
        }}
      >
        <Typography variant="h4">Dashboard</Typography>
        <Box sx={{ display: "flex", gap: 1 }}>
          <Button
            variant="outlined"
            color="primary"
            startIcon={<GenerateIcon />}
            onClick={() => setDemoDialog("generate")}
          >
            Genera Dati Demo
          </Button>
          <Button
            variant="outlined"
            color="error"
            startIcon={<ClearIcon />}
            onClick={() => setDemoDialog("clear")}
          >
            Pulisci Database
          </Button>
        </Box>
      </Box>

      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title="Eventi Totali"
            value={eventi.length}
            icon={<EventIcon sx={{ fontSize: 48 }} />}
            color="#1976d2"
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title="Confermati"
            value={eventiConfermati}
            icon={<ConfirmedIcon sx={{ fontSize: 48 }} />}
            color="#4caf50"
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title="In Preventivo"
            value={eventiPreventivo}
            icon={<PendingIcon sx={{ fontSize: 48 }} />}
            color="#ff9800"
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title="Eventi Oggi"
            value={eventiOggi}
            icon={<PeopleIcon sx={{ fontSize: 48 }} />}
            color="#9c27b0"
          />
        </Grid>
      </Grid>

      <Grid container spacing={3}>
        <Grid size={{ xs: 12, md: 6 }}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              Prossimi Eventi (30 giorni)
            </Typography>
            <List>
              {eventiProssimi.slice(0, 10).map((evento) => (
                <ListItem
                  key={evento.id}
                  component="div"
                  onClick={() => navigate(`/eventi/${evento.id}`)}
                  sx={{
                    cursor: "pointer",
                    "&:hover": { bgcolor: "action.hover" },
                  }}
                >
                  <ListItemText
                    primary={evento.descrizione || evento.codice}
                    secondary={
                      <Box
                        component="span"
                        sx={{ display: "flex", gap: 1, alignItems: "center" }}
                      >
                        <span>
                          {dayjs(evento.dataEvento).format("DD/MM/YYYY")}
                        </span>
                        <span>-</span>
                        <span>{evento.cliente?.ragioneSociale}</span>
                      </Box>
                    }
                  />
                  <Chip
                    label={getStatoLabel(evento.stato)}
                    color={getStatoColor(evento.stato) as any}
                    size="small"
                  />
                </ListItem>
              ))}
              {eventiProssimi.length === 0 && (
                <ListItem>
                  <ListItemText primary="Nessun evento nei prossimi 30 giorni" />
                </ListItem>
              )}
            </List>
          </Paper>
        </Grid>

        <Grid size={{ xs: 12, md: 6 }}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              Preventivi in Scadenza
            </Typography>
            <List>
              {eventi
                .filter(
                  (e) =>
                    e.stato === StatoEvento.Preventivo &&
                    e.dataScadenzaPreventivo,
                )
                .sort((a, b) =>
                  dayjs(a.dataScadenzaPreventivo).diff(
                    dayjs(b.dataScadenzaPreventivo),
                  ),
                )
                .slice(0, 5)
                .map((evento) => (
                  <ListItem
                    key={evento.id}
                    component="div"
                    onClick={() => navigate(`/eventi/${evento.id}`)}
                    sx={{
                      cursor: "pointer",
                      "&:hover": { bgcolor: "action.hover" },
                    }}
                  >
                    <ListItemText
                      primary={evento.descrizione || evento.codice}
                      secondary={`Scade: ${dayjs(evento.dataScadenzaPreventivo).format("DD/MM/YYYY")}`}
                    />
                    <Chip
                      label={`${evento.numeroOspiti || 0} ospiti`}
                      size="small"
                      variant="outlined"
                    />
                  </ListItem>
                ))}
              {eventi.filter((e) => e.stato === StatoEvento.Preventivo)
                .length === 0 && (
                <ListItem>
                  <ListItemText primary="Nessun preventivo in attesa" />
                </ListItem>
              )}
            </List>
          </Paper>
        </Grid>
      </Grid>

      {/* Dialog Genera Dati Demo */}
      <Dialog open={demoDialog === "generate"} onClose={handleCloseDialog}>
        <DialogTitle>Genera Dati Demo</DialogTitle>
        <DialogContent>
          {!result && !error && (
            <DialogContentText>
              Questa operazione genera dati di test per dimostrazioni:
              <br />- 15 Clienti
              <br />- 10 Location
              <br />- 12 Risorse (staff)
              <br />- 20 Articoli
              <br />- 20 Eventi con dettagli
              <br />
              <br />I dati esistenti non verranno modificati.
            </DialogContentText>
          )}
          {loading && (
            <Box sx={{ display: "flex", justifyContent: "center", py: 3 }}>
              <CircularProgress />
            </Box>
          )}
          {result && (
            <Alert severity="success" sx={{ mt: 1 }}>
              {result.message}
            </Alert>
          )}
          {error && (
            <Alert severity="error" sx={{ mt: 1 }}>
              {error}
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>
            {result ? "Chiudi" : "Annulla"}
          </Button>
          {!result && (
            <Button
              onClick={handleGenerateDemo}
              variant="contained"
              disabled={loading}
            >
              Genera
            </Button>
          )}
        </DialogActions>
      </Dialog>

      {/* Dialog Pulisci Database */}
      <Dialog open={demoDialog === "clear"} onClose={handleCloseDialog}>
        <DialogTitle>Pulisci Database</DialogTitle>
        <DialogContent>
          {!result && !error && (
            <Alert severity="warning" sx={{ mb: 2 }}>
              Attenzione: questa operazione elimina TUTTI i dati dal database!
            </Alert>
          )}
          {!result && !error && (
            <DialogContentText>
              Verranno eliminati:
              <br />- Tutti gli eventi e i relativi dettagli
              <br />- Tutti i clienti
              <br />- Tutte le location
              <br />- Tutte le risorse
              <br />- Tutti gli articoli
              <br />
              <br />
              Questa operazione non puo essere annullata.
            </DialogContentText>
          )}
          {loading && (
            <Box sx={{ display: "flex", justifyContent: "center", py: 3 }}>
              <CircularProgress />
            </Box>
          )}
          {result && (
            <Alert severity="success" sx={{ mt: 1 }}>
              Database pulito. Eliminati: {result.eventiCreati} eventi,{" "}
              {result.clientiCreati} clienti, {result.locationCreate} location,{" "}
              {result.risorseCreate} risorse, {result.articoliCreati} articoli.
            </Alert>
          )}
          {error && (
            <Alert severity="error" sx={{ mt: 1 }}>
              {error}
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>
            {result ? "Chiudi" : "Annulla"}
          </Button>
          {!result && (
            <Button
              onClick={handleClearDemo}
              variant="contained"
              color="error"
              disabled={loading}
            >
              Elimina Tutto
            </Button>
          )}
        </DialogActions>
      </Dialog>
    </Box>
  );
}
