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 { useTranslation, Trans } from "react-i18next";
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, t: any) => {
  switch (stato) {
    case StatoEvento.Scheda:
      return t("status.scheda");
    case StatoEvento.Preventivo:
      return t("status.preventivo");
    case StatoEvento.Confermato:
      return t("status.confermato");
    default:
      return t("common.unknown");
  }
};

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 { t } = useTranslation();
  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 || t("dashboard.generateError"),
      );
    } 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 || t("dashboard.clearError"),
      );
    } 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">{t("dashboard.title")}</Typography>
        <Box sx={{ display: "flex", gap: 1 }}>
          <Button
            variant="outlined"
            color="primary"
            startIcon={<GenerateIcon />}
            onClick={() => setDemoDialog("generate")}
          >
            {t("dashboard.generateDemoData")}
          </Button>
          <Button
            variant="outlined"
            color="error"
            startIcon={<ClearIcon />}
            onClick={() => setDemoDialog("clear")}
          >
            {t("dashboard.clearDatabase")}
          </Button>
        </Box>
      </Box>

      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title={t("dashboard.totalEvents")}
            value={eventi.length}
            icon={<EventIcon sx={{ fontSize: 48 }} />}
            color="#1976d2"
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title={t("dashboard.confirmed")}
            value={eventiConfermati}
            icon={<ConfirmedIcon sx={{ fontSize: 48 }} />}
            color="#4caf50"
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title={t("dashboard.inQuote")}
            value={eventiPreventivo}
            icon={<PendingIcon sx={{ fontSize: 48 }} />}
            color="#ff9800"
          />
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          <StatCard
            title={t("dashboard.eventsToday")}
            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>
              {t("dashboard.upcomingEvents")}
            </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, t)}
                    color={getStatoColor(evento.stato) as any}
                    size="small"
                  />
                </ListItem>
              ))}
              {eventiProssimi.length === 0 && (
                <ListItem>
                  <ListItemText primary={t("dashboard.noEvents")} />
                </ListItem>
              )}
            </List>
          </Paper>
        </Grid>

        <Grid size={{ xs: 12, md: 6 }}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              {t("dashboard.expiringQuotes")}
            </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={t("dashboard.expires", { date: dayjs(evento.dataScadenzaPreventivo).format("DD/MM/YYYY") })}
                    />
                    <Chip
                      label={t("dashboard.guests", { count: evento.numeroOspiti || 0 })}
                      size="small"
                      variant="outlined"
                    />
                  </ListItem>
                ))}
              {eventi.filter((e) => e.stato === StatoEvento.Preventivo)
                .length === 0 && (
                  <ListItem>
                    <ListItemText primary={t("dashboard.noQuotes")} />
                  </ListItem>
                )}
            </List>
          </Paper>
        </Grid>
      </Grid>

      {/* Dialog Genera Dati Demo */}
      <Dialog open={demoDialog === "generate"} onClose={handleCloseDialog}>
        <DialogTitle>{t("dashboard.generateDialogTitle")}</DialogTitle>
        <DialogContent>
          {!result && !error && (
            <DialogContentText>
              <Trans i18nKey="dashboard.generateDialogText" components={{ br: <br /> }} />
            </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 ? t("common.close") : t("common.cancel")}
          </Button>
          {!result && (
            <Button
              onClick={handleGenerateDemo}
              variant="contained"
              disabled={loading}
            >
              {t("common.generate")}
            </Button>
          )}
        </DialogActions>
      </Dialog>

      {/* Dialog Pulisci Database */}
      <Dialog open={demoDialog === "clear"} onClose={handleCloseDialog}>
        <DialogTitle>{t("dashboard.clearDialogTitle")}</DialogTitle>
        <DialogContent>
          {!result && !error && (
            <Alert severity="warning" sx={{ mb: 2 }}>
              {t("dashboard.clearDialogWarning")}
            </Alert>
          )}
          {!result && !error && (
            <DialogContentText>
              <Trans i18nKey="dashboard.clearDialogText" components={{ br: <br /> }} />
            </DialogContentText>
          )}
          {loading && (
            <Box sx={{ display: "flex", justifyContent: "center", py: 3 }}>
              <CircularProgress />
            </Box>
          )}
          {result && (
            <Alert severity="success" sx={{ mt: 1 }}>
              {t("dashboard.clearSuccess", {
                events: result.eventiCreati,
                clients: result.clientiCreati,
                locations: result.locationCreate,
                resources: result.risorseCreate,
                articles: result.articoliCreati
              })}
            </Alert>
          )}
          {error && (
            <Alert severity="error" sx={{ mt: 1 }}>
              {error}
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>
            {result ? t("common.close") : t("common.cancel")}
          </Button>
          {!result && (
            <Button
              onClick={handleClearDemo}
              variant="contained"
              color="error"
              disabled={loading}
            >
              {t("common.deleteAll")}
            </Button>
          )}
        </DialogActions>
      </Dialog>
    </Box>
  );
}
