import React, { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";
import {
  Box,
  Paper,
  Typography,
  Checkbox,
  FormControlLabel,
  FormGroup,
  CircularProgress,
} from "@mui/material";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import itLocale from "@fullcalendar/core/locales/it";
import { eventiApi } from "../services/api";
import { StatoEvento, getStatoColor, getStatoTextColor } from "../types";

const CalendarioPage: React.FC = () => {
  const navigate = useNavigate();
  const [showSchede, setShowSchede] = useState(true);
  const [showPreventivi, setShowPreventivi] = useState(true);
  const [showConfermati, setShowConfermati] = useState(true);

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

  // Filter events based on status checkboxes
  const filteredEventi = eventi?.filter((e) => {
    if (e.stato === StatoEvento.Scheda && !showSchede) return false;
    if (e.stato === StatoEvento.Preventivo && !showPreventivi) return false;
    if (e.stato === StatoEvento.Confermato && !showConfermati) return false;
    return true;
  });

  // Convert events to FullCalendar format
  const calendarEvents = filteredEventi?.map((evento) => ({
    id: String(evento.id),
    title: evento.descrizione || evento.cliente?.ragioneSociale || "Evento",
    start: evento.dataEvento,
    end: evento.dataEvento,
    backgroundColor: getStatoColor(evento.stato),
    borderColor: getStatoTextColor(evento.stato),
    textColor: getStatoTextColor(evento.stato),
    extendedProps: {
      evento,
    },
  }));

  const handleEventClick = (info: any) => {
    const eventoId = info.event.id;
    navigate(`/eventi/${eventoId}`);
  };

  const handleDateClick = (info: any) => {
    navigate(`/eventi/nuovo?data=${info.dateStr}`);
  };

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

  return (
    <Box>
      <Box
        display="flex"
        justifyContent="space-between"
        alignItems="center"
        mb={3}
      >
        <Typography variant="h4">Calendario Eventi</Typography>
      </Box>

      <Paper sx={{ p: 2, mb: 2 }}>
        <Typography variant="subtitle2" gutterBottom>
          Filtra per stato:
        </Typography>
        <FormGroup row>
          <FormControlLabel
            control={
              <Checkbox
                checked={showSchede}
                onChange={(e) => setShowSchede(e.target.checked)}
                sx={{
                  color: getStatoTextColor(StatoEvento.Scheda),
                  "&.Mui-checked": {
                    color: getStatoTextColor(StatoEvento.Scheda),
                  },
                }}
              />
            }
            label={
              <Box
                sx={{
                  px: 1,
                  py: 0.5,
                  borderRadius: 1,
                  backgroundColor: getStatoColor(StatoEvento.Scheda),
                  color: getStatoTextColor(StatoEvento.Scheda),
                }}
              >
                Schede
              </Box>
            }
          />
          <FormControlLabel
            control={
              <Checkbox
                checked={showPreventivi}
                onChange={(e) => setShowPreventivi(e.target.checked)}
                sx={{
                  color: getStatoTextColor(StatoEvento.Preventivo),
                  "&.Mui-checked": {
                    color: getStatoTextColor(StatoEvento.Preventivo),
                  },
                }}
              />
            }
            label={
              <Box
                sx={{
                  px: 1,
                  py: 0.5,
                  borderRadius: 1,
                  backgroundColor: getStatoColor(StatoEvento.Preventivo),
                  color: getStatoTextColor(StatoEvento.Preventivo),
                }}
              >
                Preventivi
              </Box>
            }
          />
          <FormControlLabel
            control={
              <Checkbox
                checked={showConfermati}
                onChange={(e) => setShowConfermati(e.target.checked)}
                sx={{
                  color: getStatoTextColor(StatoEvento.Confermato),
                  "&.Mui-checked": {
                    color: getStatoTextColor(StatoEvento.Confermato),
                  },
                }}
              />
            }
            label={
              <Box
                sx={{
                  px: 1,
                  py: 0.5,
                  borderRadius: 1,
                  backgroundColor: getStatoColor(StatoEvento.Confermato),
                  color: getStatoTextColor(StatoEvento.Confermato),
                }}
              >
                Confermati
              </Box>
            }
          />
        </FormGroup>
      </Paper>

      <Paper sx={{ p: 2 }}>
        <FullCalendar
          plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
          initialView="dayGridMonth"
          locale={itLocale}
          headerToolbar={{
            left: "prev,next today",
            center: "title",
            right: "dayGridMonth,timeGridWeek,timeGridDay",
          }}
          events={calendarEvents}
          eventClick={handleEventClick}
          dateClick={handleDateClick}
          height="auto"
          eventDisplay="block"
          dayMaxEvents={3}
          eventContent={(arg) => (
            <Box
              sx={{
                p: 0.5,
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
                fontSize: "0.85em",
                fontWeight: 500,
              }}
            >
              {arg.event.extendedProps.evento.oraInizio && (
                <span style={{ marginRight: 4 }}>
                  {arg.event.extendedProps.evento.oraInizio.substring(0, 5)}
                </span>
              )}
              {arg.event.title}
            </Box>
          )}
        />
      </Paper>
    </Box>
  );
};

export default CalendarioPage;
