import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
  Box,
  Typography,
  Paper,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Button,
} from "@mui/material";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import { useNavigate } from "react-router-dom";
import dayjs from "dayjs";
import { eventiService } from "../services/eventiService";

export default function CalendarioPage() {
  const navigate = useNavigate();
  const [dateRange, setDateRange] = useState({
    start: dayjs().startOf("month").format("YYYY-MM-DD"),
    end: dayjs().endOf("month").format("YYYY-MM-DD"),
  });
  const [newEventDialog, setNewEventDialog] = useState<{
    open: boolean;
    date: string;
    formattedDate: string;
  }>({
    open: false,
    date: "",
    formattedDate: "",
  });

  const { data: eventi = [] } = useQuery({
    queryKey: ["calendario", dateRange],
    queryFn: () => eventiService.getCalendario(dateRange.start, dateRange.end),
  });

  const handleDateClick = (info: any) => {
    // Mostra dialog per chiedere se creare nuovo evento
    setNewEventDialog({
      open: true,
      date: info.dateStr,
      formattedDate: dayjs(info.dateStr).format("DD/MM/YYYY"),
    });
  };

  const handleCreateEvent = () => {
    // Naviga alla pagina nuovo evento con la data preselezionata
    navigate("/eventi/0", { state: { dataEvento: newEventDialog.date } });
    setNewEventDialog({ open: false, date: "", formattedDate: "" });
  };

  const handleCloseDialog = () => {
    setNewEventDialog({ open: false, date: "", formattedDate: "" });
  };

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

  const handleDatesSet = (info: any) => {
    setDateRange({
      start: dayjs(info.start).format("YYYY-MM-DD"),
      end: dayjs(info.end).format("YYYY-MM-DD"),
    });
  };

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Calendario Eventi
      </Typography>

      <Paper sx={{ p: 2 }}>
        <FullCalendar
          plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
          initialView="dayGridMonth"
          headerToolbar={{
            left: "prev,next today",
            center: "title",
            right: "dayGridMonth,timeGridWeek,timeGridDay",
          }}
          locale="it"
          events={eventi.map((e) => ({
            id: String(e.id),
            title: e.title,
            start: e.start,
            end: e.end,
            backgroundColor: e.color,
            borderColor: e.color,
            extendedProps: {
              cliente: e.cliente,
              location: e.location,
              numeroOspiti: e.numeroOspiti,
            },
          }))}
          dateClick={handleDateClick}
          eventClick={handleEventClick}
          datesSet={handleDatesSet}
          height="auto"
          eventTimeFormat={{
            hour: "2-digit",
            minute: "2-digit",
            meridiem: false,
          }}
          buttonText={{
            today: "Oggi",
            month: "Mese",
            week: "Settimana",
            day: "Giorno",
          }}
        />
      </Paper>

      {/* Dialog per creazione nuovo evento */}
      <Dialog open={newEventDialog.open} onClose={handleCloseDialog}>
        <DialogTitle>Nuovo Evento</DialogTitle>
        <DialogContent>
          <DialogContentText>
            Vuoi creare un nuovo evento per il giorno{" "}
            <strong>{newEventDialog.formattedDate}</strong>?
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>Annulla</Button>
          <Button onClick={handleCreateEvent} variant="contained" autoFocus>
            Crea Evento
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
