"use client"

import type React from "react"
import { useMemo, useState } from "react"
import { Box, Grid, Typography } from "@mui/material"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import FontAwesome from "@/shared/components/fontawesome"
import { faSquarePlus } from "@fortawesome/free-solid-svg-icons"
import { AddButton } from "@/shared/components/table/styles"
import { CalendarHeader, DayCell, MonthBox, MonthTitle, StyledYearContainer, WeekdayHeader } from "./styles"
import { PeriodPopover } from "./period-popover"
import { CalendarEvent } from "@/hooks/use-calendar"

interface VacanceYearCalendarProps {
  date: Date
  isToday: (date: Date) => boolean
  handleTabAdd: () => void
  zoomLevel: number
  yearCalendarData: {
    year: number
    weekdays: string[]
    months: {
      name: string
      days: {
        date: Date
        day: number
        periods: CalendarEvent[]
      }[]
    }[]
  }
  isChild?: boolean
  
}

export default function VacanceYearCalendar({
  date,
  isToday,
  handleTabAdd,
  zoomLevel,
  yearCalendarData,
  isChild = false,
}: VacanceYearCalendarProps) {
  
  const { year, weekdays, months } = yearCalendarData
  const [popoverAnchorEl, setPopoverAnchorEl] = useState<HTMLElement | null>(null)
  const [selectedDate, setSelectedDate] = useState<Date | null>(null)
  const [selectedPeriods, setSelectedPeriods] = useState<CalendarEvent[]>([])

  const cellSize = useMemo(() => {
    return 22 + (zoomLevel / 100) * 18
  }, [zoomLevel])
  const backgroundColor =  isChild ? 'primary.lighter' : undefined

  const handleDayClick = (event: React.MouseEvent<HTMLElement>, day: Date, periods: CalendarEvent[]) => {
    if (periods.length > 0) {
      setPopoverAnchorEl(event.currentTarget)
      setSelectedDate(day)
      setSelectedPeriods(periods)
    }
  }

  const handleClosePopover = () => {
    setPopoverAnchorEl(null)
  }

  const belongsToDisplayedMonth = (date: Date, monthIndex: number) => {
    return date.getMonth() === monthIndex
  }

  return (
    <StyledYearContainer sx={{backgroundColor}}>
      <CalendarHeader sx={{backgroundColor}}>
        <Box flexGrow={1} />
        <Typography
          sx={{
            fontSize: "23px",
            fontWeight: 600,
            color: "primary.main",
            position: "absolute",
            left: "50%",
            transform: "translateX(-50%)",
          }}
        >
          {year}
        </Typography>
        <CustomTooltip title={"Ajouter Une Nouvelle période"} arrow>
          <AddButton
            onClick={handleTabAdd}
            variant="contained"
            endIcon={<FontAwesome icon={faSquarePlus} width={18} />}
          >
            Nouvelle période
          </AddButton>
        </CustomTooltip>
      </CalendarHeader>

      <Grid container spacing={2} sx={{ pt: 2 }}>
        {months.map((month, monthIndex) => (
          <Grid item xs={12} sm={6} md={4} lg={3} key={month.name}>
            <MonthBox >
              <MonthTitle variant="subtitle1">{month.name}</MonthTitle>

              <Grid container spacing={0.5}>
                {weekdays.map((weekday) => (
                  <Grid item xs={1.7} key={weekday}>
                    <WeekdayHeader>{weekday}</WeekdayHeader>
                  </Grid>
                ))}
              </Grid>

              <Grid container spacing={0.5} sx={{ marginTop: (theme) => theme.spacing(1) }}>
                {month.days.map((day, idx) => {
                  const isDisplayedMonth = belongsToDisplayedMonth(day.date, monthIndex)
                  return (
                    <Grid item xs={1.7} key={`${day.day}-${idx}`}>
                      <DayCell
                        isToday={isToday(day.date)}
                        isCurrentMonth={isDisplayedMonth}
                        hasPeriods={day.periods.length > 0}
                        onClick={(e) => handleDayClick(e, day.date, day.periods)}
                        size={cellSize}
                      >
                        {day.day}
                      </DayCell>
                    </Grid>
                  )
                })}
              </Grid>
            </MonthBox>
          </Grid>
        ))}
      </Grid>

      {selectedDate ? (
        <PeriodPopover
          open={popoverAnchorEl}
          onClose={handleClosePopover}
          date={selectedDate}
          periods={selectedPeriods}
        />
      ): <></>}
    </StyledYearContainer>
  )
}