'use client';

import type React from 'react';

import { useEffect, useState, useCallback, useRef, type ReactNode } from 'react';
import {
  IconButton,
  Stack,
  Box,
  Slider,
  Typography,
  FormControl,
  Select,
  MenuItem,
  ListItemIcon,
  ListItemText,
} from '@mui/material';
import type { SelectChangeEvent } from '@mui/material/Select';
import FontAwesome from '@/shared/components/fontawesome';
import { WhiteIconButtonStyle } from '@/shared/theme/css';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import SvgColor from '@/shared/components/svg-color';
import {
  faCircleChevronLeft,
  faCircleChevronRight,
  faPrint,
  faRotate,
  faCheck,
} from '@fortawesome/free-solid-svg-icons';
import { alpha, styled } from '@mui/system';
import { lightColor, mainButtonStyle } from '@/shared/components/table/styles';
import TableFilter from '@/shared/components/table/table-filter';
import { TableType, TimeUnit } from '@/shared/types/common';
import { DatePickerPopover, DurationFilter } from './date-picker-popover';
import { Dayjs } from 'dayjs';
import ConditionalComponent from '../table/ConditionalComponent';

const CustomSlider = styled(Slider)(({ theme }) => ({
  color: '#8B7FFF',
  height: 4,
  '& .MuiSlider-thumb': {
    height: 16,
    width: 16,
    backgroundColor: '#fff',
    border: '6px solid #8B7FFF',
    boxShadow: `0 0 0 3px white`,
    transition: 'box-shadow 0.1s ease-in-out', // Faster transition
  },
  '& .MuiSlider-track': {
    height: 1,
    borderRadius: 2,
    transition: 'none', // Remove transition for better performance
  },
  '& .MuiSlider-rail': {
    height: 3,
    borderRadius: 2,
    backgroundColor: alpha(theme.palette.primary.main, 0.2),
  },
}));

export const ExtendedWhiteIconButtonStyle = {
  ...WhiteIconButtonStyle,
  padding: 0.9,
};


interface ScheduleToolbarProps {
  date: Date;
  onDateChange: (date: Dayjs | Date, timeUnit?: TimeUnit) => void;
  onZoomChange: (zoom: number) => void;
  onFilters: (key: string, value: string, condition: string) => void;
  onResetFilters: () => void;
  initialColumns: { id: string; label: string; type?: string }[];
  type: TableType;
  customAction?: ReactNode;
  timeUnit?: TimeUnit;
  goToPreviousMonth?: () => void;
  goToNextMonth?: () => void;
  isChild?: boolean;
  rightAction?: ReactNode;
  onSelectType?: (selectType: LeaveType) => void;
  onDurationFilterChange?: (filter: DurationFilter | null) => void;
}

export enum LeaveType {
  Absence = 'absence',
  Conge = 'conge',
}

export function ScheduleToolbar({
  date,
  onDateChange,
  onZoomChange,
  onFilters,
  onResetFilters,
  initialColumns,
  type,
  customAction,
  timeUnit = 'day',
  goToPreviousMonth,
  goToNextMonth,
  isChild = false,
  rightAction,
  onSelectType,
  onDurationFilterChange
}: ScheduleToolbarProps) {
  const [calendarAnchor, setCalendarAnchor] = useState<null | HTMLElement>(null);
  const [zoomValue, setZoomValue] = useState<number>(50);
  const [leaveType, setLeaveType] = useState<LeaveType | ''>('');

  // Debounce timer ref
  const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);

  const handleLeaveTypeChange = (event: SelectChangeEvent<LeaveType | ''>) => {
    const value = event.target.value as LeaveType;
    if (onSelectType) {
      onSelectType(value);
    }
    setLeaveType(value);
  };

  const handlePrev = () => {
    const newDate = new Date(date);
    if (timeUnit === 'day') {
      newDate.setDate(date.getDate() - 1);
    } else if (timeUnit === 'month' && goToPreviousMonth) {
      goToPreviousMonth();
      return;
    } else if (timeUnit === 'year') {
      newDate.setFullYear(date.getFullYear() - 1);
    }
    onDateChange(newDate);
  };

  useEffect(() => {
    console.log(date);
  }, [date]);

  const handleNext = () => {
    const newDate = new Date(date);
    if (timeUnit === 'day') {
      newDate.setDate(date.getDate() + 1);
    } else if (timeUnit === 'month' && goToNextMonth) {
      goToNextMonth();
      return;
    } else if (timeUnit === 'year') {
      newDate.setFullYear(date.getFullYear() + 1);
    }
    onDateChange(newDate);
  };

  const handleCalendarClick = (event: React.MouseEvent<HTMLElement>) => {
    setCalendarAnchor(event.currentTarget);
  };

  const handleCalendarClose = () => {
    setCalendarAnchor(null);
  };

  // Debounced zoom change handler
  const handleZoomChange = useCallback(
    (_event: Event, newValue: number | number[]) => {
      const zoom = Array.isArray(newValue) ? newValue[0] : newValue;

      // Update local state immediately for smooth UI
      setZoomValue(zoom);

      // Clear existing timer
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }

      // Set new timer to call parent's onZoomChange after delay
      debounceTimerRef.current = setTimeout(() => {
        onZoomChange(zoom);
      }, 150); // 150ms debounce delay
    },
    [onZoomChange]
  );

  // Cleanup timer on unmount
  useEffect(() => {
    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
    };
  }, []);

  const getPrevTooltip = () => {
    switch (timeUnit) {
      case 'day':
        return 'Jour précédent';
      case 'month':
        return 'Mois précédent';
      case 'year':
        return 'Année précédente';
      default:
        return 'Précédent';
    }
  };

  const getNextTooltip = () => {
    switch (timeUnit) {
      case 'day':
        return 'Jour suivant';
      case 'month':
        return 'Mois suivant';
      case 'year':
        return 'Année suivante';
      default:
        return 'Suivant';
    }
  };

  return (
    <Box sx={{ width: "100%", display: 'flex', justifyContent: 'center', pb: 1 }}>
      <Stack direction="row" spacing={1} justifyContent={"center"} alignItems="center" sx={{ width: '100%' }}>
        {customAction ? customAction : <></>}
        <CustomTooltip title="Calendrier" arrow>
          <IconButton sx={lightColor} onClick={handleCalendarClick}>
            <SvgColor
              src="/assets/icons/ic_date.svg"
              sx={{
                width: 18,
                height: 18,
              }}
            />
          </IconButton>
        </CustomTooltip>

        <DatePickerPopover
          open={Boolean(calendarAnchor)}
          anchorEl={calendarAnchor}
          onClose={handleCalendarClose}
          date={date}
          onDateChange={onDateChange}
          isPlanning={true}
          {...(onDurationFilterChange && { onDurationFilterChange })}
        />

        {customAction ? (
          <></>
        ) : (
          <CustomTooltip title="Imprimer" arrow>
            <IconButton sx={ExtendedWhiteIconButtonStyle} onClick={() => void 0}>
              <FontAwesome icon={faPrint} width={18} />
            </IconButton>
          </CustomTooltip>
        )}

        <CustomTooltip title={getPrevTooltip()} arrow>
          <IconButton sx={mainButtonStyle} onClick={handlePrev}>
            <FontAwesome width={30} icon={faCircleChevronLeft} />
          </IconButton>
        </CustomTooltip>

        <Box
          sx={{
            height: 35,
            width: 300,
            display: 'flex',
            alignItems: 'center',
            mx: 2,
            bgcolor: isChild ? 'primary.lighter' : 'white',
            borderRadius: 5,
            px: 1,
          }}
        >
          <CustomSlider
            value={zoomValue}
            onChange={handleZoomChange}
            aria-labelledby="continuous-slider"
            // Add these props for better performance
            step={1}
            min={0}
            max={100}
          />

          <Typography sx={{ marginLeft: 2, color: '#6B7280', fontSize: '0.875rem' }}>
            {zoomValue}%
          </Typography>
        </Box>

        <CustomTooltip title={getNextTooltip()} arrow>
          <IconButton sx={mainButtonStyle} onClick={handleNext}>
            <FontAwesome width={30} icon={faCircleChevronRight} />
          </IconButton>
        </CustomTooltip>

        <CustomTooltip title="Rafraîchir" arrow>
          <IconButton sx={isChild ? lightColor : ExtendedWhiteIconButtonStyle} onClick={onResetFilters}>
            <FontAwesome icon={faRotate} width={18} />
          </IconButton>
        </CustomTooltip>

        <TableFilter
          onResetFilters={onResetFilters}
          onFilters={onFilters}
          initialColumns={initialColumns}
          type={type}
          isChild={isChild}
        />

        <ConditionalComponent isValid={!!rightAction}>{rightAction}</ConditionalComponent>

        <FormControl
          size="small"
          sx={{
            minWidth: 180,
            '& .MuiInputBase-root': {
              borderRadius: 2,
              backgroundColor: 'background.paper',
              boxShadow: (theme) => `0 0 0 1px ${theme.palette.divider}`,
              transition: 'all 0.2s ease-in-out',
              '&:hover': {
                boxShadow: (theme) => `0 0 0 1px ${theme.palette.primary.main}`,
              },
              '&.Mui-focused': {
                boxShadow: (theme) => `0 0 0 2px ${theme.palette.primary.main}`,
              },
            },
          }}
        >
          <Select
            value={leaveType}
            displayEmpty
            onChange={handleLeaveTypeChange}
            variant="outlined"
            inputProps={{ 'aria-label': 'Type de congé/absence' }}
            IconComponent={(props) => (
              <FontAwesome icon={faCircleChevronRight} {...props} width={14} color="#8B7FFF" />
            )}
            renderValue={(selected) => {
              if (!selected) {
                return (
                  <Typography
                    sx={{
                      color: 'text.secondary',
                      fontStyle: 'italic',
                      fontSize: '0.9rem',
                    }}
                  >
                    Type
                  </Typography>
                );
              }
              return (
                <Stack direction="row" spacing={1} alignItems="center">
                  <FontAwesome
                    icon={faCheck}
                    width={13}
                    color="#8B7FFF"
                  />
                  <Typography
                    sx={{
                      textTransform: 'capitalize',
                      fontWeight: 500,
                      fontSize: '0.9rem',
                      color: 'text.primary',
                    }}
                  >
                    {selected}
                  </Typography>
                </Stack>
              );
            }}
            MenuProps={{
              PaperProps: {
                elevation: 4,
                sx: {
                  mt: 0.5,
                  borderRadius: 2,
                  backgroundColor: 'background.paper',
                  border: '1px solid',
                  borderColor: 'divider',
                  '& .MuiMenuItem-root': {
                    px: 2,
                    py: 1,
                    fontSize: '0.9rem',
                    '&:hover': {
                      backgroundColor: 'action.hover',
                    },
                    '&.Mui-selected': {
                      backgroundColor: 'primary.lighter',
                      color: 'primary.main',
                      '&:hover': {
                        backgroundColor: 'primary.light',
                      },
                    },
                  },
                },
              },
            }}
          >
            <MenuItem disabled value="">
              <em>Sélectionner…</em>
            </MenuItem>

            <MenuItem value={LeaveType.Absence}>
              <ListItemIcon sx={{ minWidth: 28, color: 'primary.main' }}>
                {leaveType === LeaveType.Absence && (
                  <FontAwesome icon={faCheck} width={13} />
                )}
              </ListItemIcon>
              <ListItemText primary="Absence" />
            </MenuItem>

            <MenuItem value={LeaveType.Conge}>
              <ListItemIcon sx={{ minWidth: 28, color: 'primary.main' }}>
                {leaveType === LeaveType.Conge && (
                  <FontAwesome icon={faCheck} width={13} />
                )}
              </ListItemIcon>
              <ListItemText primary="Congé" />
            </MenuItem>
          </Select>
        </FormControl>

      </Stack>
    </Box>
  );
}