"use client"

import type React from "react"
import { useState } from "react"
import {
  Box,
  ToggleButtonGroup,
  ToggleButton,
  TextField,
  Typography,
  Divider,
  Stack,
  IconButton
} from "@mui/material"
import { LocalizationProvider } 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"
import FontAwesome from "@/shared/components/fontawesome"
import { faFilter, faUserTie, faCheck, faXmark } from "@fortawesome/free-solid-svg-icons"
import { faClock } from "@fortawesome/free-regular-svg-icons"
import ConditionalComponent from "../table/ConditionalComponent"

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

export interface DurationFilter {
  enabled: boolean
  startHour: string
  startMinute: string
  endHour: string
  endMinute: string
  filterMode: 'drivers' | 'slots'
}

export function DatePickerPopover({
  open,
  anchorEl,
  onClose,
  date,
  onDateChange,
  isPlanning,
  onDurationFilterChange
}: DatePickerPopoverProps) {
  const [dateView, setDateView] = useState<TimeUnit>("day")
  const [durationFilter, setDurationFilter] = useState<DurationFilter>({
    enabled: false,
    startHour: "08",
    startMinute: "00",
    endHour: "18",
    endMinute: "00",
    filterMode: 'drivers',
  })

  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 handleTimeChange = (field: keyof DurationFilter, value: string) => {
    const numValue = parseInt(value)

    if (field.includes('Hour')) {
      if (numValue < 0 || numValue > 23 || value.length > 2) return
    } else if (field.includes('Minute')) {
      if (numValue < 0 || numValue > 59 || value.length > 2) return
    }

    const updatedFilter = { ...durationFilter, [field]: value.padStart(2, '0') }
    setDurationFilter(updatedFilter)

    if (durationFilter.enabled && onDurationFilterChange) {
      onDurationFilterChange(updatedFilter)
    }
  }

  const handleFilterModeToggle = () => {
    const newMode = durationFilter.filterMode === 'drivers' ? 'slots' : 'drivers'
    const updatedFilter = {
      ...durationFilter,
      filterMode: newMode,
      enabled: true
    } as DurationFilter
    setDurationFilter(updatedFilter)

    if (onDurationFilterChange) {
      onDurationFilterChange(updatedFilter)
    }
  }

  const handleEnableFilter = () => {
    const updatedFilter = { ...durationFilter, enabled: !durationFilter.enabled }
    setDurationFilter(updatedFilter)

    if (onDurationFilterChange) {
      onDurationFilterChange(updatedFilter.enabled ? updatedFilter : null)
    }
  }

  const getDatePickerViews = () => {
    switch (dateView) {
      case "year":
        return ["year"]
      case "month":
        return ["year", "month"]
      case "day":
        return ["year", "month", "day"]
      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, minWidth: 320 }}>
        {/* Date View Toggle */}
        <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>
            <ToggleButton value="day" aria-label="day view">Jour</ToggleButton>
          </ToggleButtonGroup>
        </Box>

        {/* Date Picker */}
        <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>

        {/* Duration Filter Section - Always visible in day view */}
        {isPlanning && dateView === "day" && (
          <>
            <Divider sx={{ my: 2 }} />

            <Box>
              {/* Header with Enable/Disable Toggle */}
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <FontAwesome icon={faFilter} width={14} color="primary.main" />
                  <Typography variant="body2" fontWeight={600} color="primary.main">
                    Filtrer par durée
                  </Typography>
                </Box>

                {/* Enable/Disable Switch */}
                <IconButton
                  size="small"
                  onClick={handleEnableFilter}
                  sx={{
                    width: 32,
                    height: 32,
                    bgcolor: durationFilter.enabled ? 'primary.main' : 'grey.300',
                    color: 'white',
                    '&:hover': {
                      bgcolor: durationFilter.enabled ? 'primary.dark' : 'grey.400',
                    },
                    transition: 'all 0.2s'
                  }}
                >
                  <FontAwesome
                    icon={faCheck}
                    width={14}
                  />
                </IconButton>
              </Box>

              {/* Time Input Fields - Always visible */}
              <ConditionalComponent isValid={durationFilter.enabled}>

                <Box sx={{ mb: 2 }}>
                  <Stack spacing={2}>
                    {/* Start Time */}
                    <Box>
                      <Typography variant="caption" color="text.secondary" sx={{ mb: 0.5, display: 'block' }}>
                        Heure de début
                      </Typography>
                      <Stack direction="row" spacing={1} alignItems="center">
                        <TextField
                          size="small"
                          type="number"
                          value={durationFilter.startHour}
                          onChange={(e) => handleTimeChange('startHour', e.target.value)}
                          disabled={!durationFilter.enabled}
                          inputProps={{
                            min: 0,
                            max: 23,
                            style: { textAlign: 'center' }
                          }}
                          sx={{ width: 70 }}
                          placeholder="HH"
                        />
                        <Typography variant="h6" color="text.secondary">:</Typography>
                        <TextField
                          size="small"
                          type="number"
                          value={durationFilter.startMinute}
                          onChange={(e) => handleTimeChange('startMinute', e.target.value)}
                          disabled={!durationFilter.enabled}
                          inputProps={{
                            min: 0,
                            max: 59,
                            style: { textAlign: 'center' }
                          }}
                          sx={{ width: 70 }}
                          placeholder="MM"
                        />
                      </Stack>
                    </Box>

                    {/* End Time */}
                    <Box>
                      <Typography variant="caption" color="text.secondary" sx={{ mb: 0.5, display: 'block' }}>
                        Heure de fin
                      </Typography>
                      <Stack direction="row" spacing={1} alignItems="center">
                        <TextField
                          size="small"
                          type="number"
                          value={durationFilter.endHour}
                          onChange={(e) => handleTimeChange('endHour', e.target.value)}
                          disabled={!durationFilter.enabled}
                          inputProps={{
                            min: 0,
                            max: 23,
                            style: { textAlign: 'center' }
                          }}
                          sx={{ width: 70 }}
                          placeholder="HH"
                        />
                        <Typography variant="h6" color="text.secondary">:</Typography>
                        <TextField
                          size="small"
                          type="number"
                          value={durationFilter.endMinute}
                          onChange={(e) => handleTimeChange('endMinute', e.target.value)}
                          disabled={!durationFilter.enabled}
                          inputProps={{
                            min: 0,
                            max: 59,
                            style: { textAlign: 'center' }
                          }}
                          sx={{ width: 70 }}
                          placeholder="MM"
                        />
                      </Stack>
                    </Box>
                  </Stack>
                </Box>

                <ConditionalComponent isValid={durationFilter.enabled}>
                  <Box
                    sx={{
                      p: 1.5,
                      bgcolor: 'grey.50',
                      borderRadius: 1,
                      border: '1px solid',
                      borderColor: 'divider',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      mb: 2
                    }}
                  >
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Typography variant="caption" fontWeight={500}>
                        {durationFilter.filterMode === 'drivers'
                          ? 'Chauffeurs disponibles'
                          : 'Trajets dans la durée'}
                      </Typography>
                    </Box>

                    <IconButton
                      size="small"
                      onClick={handleFilterModeToggle}
                      sx={{
                        width: 36,
                        height: 36,
                        bgcolor: durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main',
                        color: 'white',
                        '&:hover': {
                          bgcolor: durationFilter.filterMode === 'drivers' ? 'primary.dark' : 'info.dark',
                          transform: 'scale(1.05)'
                        },
                        transition: 'all 0.2s'
                      }}
                    >
                      <FontAwesome
                        icon={durationFilter.filterMode === 'drivers' ? faUserTie : faClock}
                        width={16}
                      />
                    </IconButton>
                  </Box>
                </ConditionalComponent>


                <Box
                  sx={{
                    p: 1.5,
                    bgcolor: 'primary.lighter',
                    borderRadius: 1,
                    border: '1px solid',
                    borderColor: 'primary.main'
                  }}
                >
                  <Typography variant="caption" color="primary.main" fontWeight={600}>
                    Durée: {durationFilter.startHour}:{durationFilter.startMinute} → {durationFilter.endHour}:{durationFilter.endMinute}
                  </Typography>
                </Box>

              </ConditionalComponent>


            </Box>
          </>
        )}
      </Box>
    </CustomPopover>
  )
}