"use client"

import type React from "react"
import { useState } from "react"
import { Box, ToggleButtonGroup, ToggleButton } from "@mui/material"
import { LocalizationProvider, DatePicker } from "@mui/x-date-pickers"
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns"
import { fr } from "date-fns/locale"
import CustomPopover from "../custom-popover"
import type { Dayjs } from "dayjs"
import type { TimeUnit } from "@/shared/types/common"
import { StyledDatePicker } from "@/shared/theme/css"
import { CustomDateIcon } from "../form/form-field"

interface DatePickerPopoverProps {
  open: boolean
  anchorEl: HTMLElement | null
  onClose: () => void
  date: Date
  onDateChange: (date: Dayjs | Date, timeUnit: TimeUnit) => void
}

export function DatePickerPopover({ open, anchorEl, onClose, date, onDateChange }: DatePickerPopoverProps) {
  const [dateView, setDateView] = useState<TimeUnit>("month")

  const handleDateChange = (newDate: Dayjs | Date | null) => {
    if (newDate) {
      onDateChange(newDate, dateView)
    }
  }

  const handleDateViewChange = (_event: React.MouseEvent<HTMLElement>, newView: TimeUnit | null) => {
    if (newView) {
      setDateView(newView)
      onDateChange(date, newView)
    }
  }

  const getDatePickerViews = () => {
    switch (dateView) {
      case "year":
        return ["year"]
      case "month":
      default:
        return ["year", "month"]
    }
  }

  return (
    <CustomPopover
      arrow="top-right"
      open={anchorEl}
      anchorEl={anchorEl}
      onClose={onClose}
      hiddenArrow
      sx={{
        mt: 1,
        borderRadius: 4,
      }}
    >
      <Box sx={{ p: 2 }}>
        <Box sx={{ mb: 2 }}>
          <ToggleButtonGroup
            value={dateView}
            exclusive
            onChange={handleDateViewChange}
            aria-label="date view"
            size="small"
            sx={{ mb: 1, justifyContent: "center", display: "flex" }}
          >
            <ToggleButton value="year" aria-label="year view">
              Année
            </ToggleButton>
            <ToggleButton value="month" aria-label="month view">
              Mois
            </ToggleButton>
          </ToggleButtonGroup>
        </Box>

        <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
          <StyledDatePicker
            label={dateView === "year" ? "Année" : "Mois et Année"}
            value={date}
            onChange={handleDateChange}
            views={getDatePickerViews() as any}
            openTo={dateView}
            slots={{ openPickerIcon: () => <CustomDateIcon  />}}
          />
        </LocalizationProvider>
      </Box>
    </CustomPopover>
  )
}

