'use client';

import { useState } from 'react';
import {
  IconButton,
  Stack,
  Box,
  Typography,
  FormControl,
  Select,
  MenuItem,
  Popover,
} from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import SvgColor from '@/shared/components/svg-color';
import {
  faCircleChevronLeft,
  faCircleChevronRight,
  faPrint,
  faRotate,
  faPlus,
  faChevronLeft,
  faChevronRight,
  faSquarePlus,
} from '@fortawesome/free-solid-svg-icons';
import { 
  format, 
  startOfWeek, 
  endOfWeek, 
  addMonths, 
  subMonths, 
  addWeeks, 
  subWeeks, 
  addDays, 
  subDays,
} from 'date-fns';
import { fr } from 'date-fns/locale';
import CalendarFilter from './calendar-filter';
import {
  CustomSlider,
  ExtendedWhiteIconButtonStyle,
  toolbarContainerStyle,
  firstRowStyle,
  navigationButtonStyle,
  sliderContainerStyle,
  zoomTextStyle,
  secondRowStyle,
  viewSelectStyle,
  dateDisplayStyle,
  createEventButtonStyle,
  menuPaperProps,
} from '../styles/schedule-toolbar-styles';
import { CalendarViewType } from '../types/calendar-types';
import { AddButton } from '@/shared/components/table/styles';
import ViewToggle from '@/shared/sections/planning/components/view-toggle';
import { DatePicker } from '@mui/x-date-pickers';

interface ScheduleToolbarProps {
  date: Date;
  view: CalendarViewType;
  onViewChange: (view: CalendarViewType) => void;
  onDateChange: (date: Date) => void;
  onZoomChange: (zoom: number) => void;
  onFilters: (key: string, value: string, condition: string) => void;
  onResetFilters: () => void;
  onCreateEvent: () => void;
  initialColumns: {
    id: string;
    label: string;
    type?: string;
    options?: { value: string; label: string; }[];
  }[];
  type: string;
  viewMode: 'calendar' | 'table';
  onViewToggle: () => void;
}

export function ScheduleToolbar({
  date,
  view,
  onViewChange,
  onDateChange,
  onFilters,
  onResetFilters,
  onCreateEvent,
  onZoomChange,
  initialColumns,
  type,
  viewMode,
  onViewToggle,
}: ScheduleToolbarProps) {
  const [calendarAnchor, setCalendarAnchor] = useState<null | HTMLElement>(null);
  const [zoom, setZoom] = useState(50);
  const [datePickerOpen, setDatePickerOpen] = useState(false);
  const [datePickerAnchor, setDatePickerAnchor] = useState<HTMLElement | null>(null);

  const handlePrevious = () => {
    const newDate = view === 'dayGridMonth'
      ? subMonths(date, 1)
      : view === 'timeGridWeek'
      ? subWeeks(date, 1)
      : subDays(date, 1);
    onDateChange(newDate);
  };

  const handleNext = () => {
    const newDate = view === 'dayGridMonth'
      ? addMonths(date, 1)
      : view === 'timeGridWeek'
      ? addWeeks(date, 1)
      : addDays(date, 1);
    onDateChange(newDate);
  };

  const handlePrint = () => {
    window.print();
  };

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

  const handleDatePickerClose = () => {
    setDatePickerOpen(false);
    setDatePickerAnchor(null);
  };

  const handleDatePickerChange = (newDate: Date | null) => {
    if (newDate) {
      onDateChange(newDate);
      handleDatePickerClose();
    }
  };

  const getFormattedDate = (date: Date, view: string) => {
    switch (view) {
      case 'dayGridMonth':
        return format(date, 'MMMM yyyy', { locale: fr });
      case 'timeGridWeek':
        const start = startOfWeek(date, { locale: fr, weekStartsOn: 1 });
        const end = endOfWeek(date, { locale: fr, weekStartsOn: 1 });
        return `${format(start, 'dd')} - ${format(end, 'dd')} ${format(date, 'MMMM yyyy', { locale: fr })}`;
      case 'timeGridDay':
        return format(date, 'EEEE dd MMMM yyyy', { locale: fr });
      default:
        return format(date, 'EEEE dd MMMM yyyy', { locale: fr });
    }
  };

  const handleZoomChange = (_event: Event, newValue: number | number[]) => {
    const newZoom = newValue as number;
    setZoom(newZoom);
    onZoomChange(newZoom);
  };

  return (
    <Box sx={toolbarContainerStyle}>
      {/* First row */}
      <Stack direction="row" spacing={1} alignItems="center" sx={firstRowStyle}>
        <CustomTooltip title="Sélectionner une date" arrow>
          <IconButton sx={ExtendedWhiteIconButtonStyle} onClick={handleCalendarClick}>
            <SvgColor src="/assets/icons/ic_date.svg" sx={{ width: 18, height: 18 }} />
          </IconButton>
        </CustomTooltip>

        <CustomTooltip title="Précédent" arrow>
          <IconButton sx={navigationButtonStyle} onClick={handlePrevious}>
            <FontAwesome icon={faChevronLeft} width={20} color="white" />
          </IconButton>
        </CustomTooltip>

        <Box sx={sliderContainerStyle}>
          <CustomSlider
            value={zoom}
            onChange={handleZoomChange}
            aria-labelledby="continuous-slider"
            min={25}
            max={200}
            defaultValue={50}
          />
          <Typography sx={zoomTextStyle}>
            {zoom}%
          </Typography>
        </Box>

        <CustomTooltip title="Suivant" arrow>
          <IconButton sx={navigationButtonStyle} onClick={handleNext}>
            <FontAwesome icon={faChevronRight} width={20} color="white" />
          </IconButton>
        </CustomTooltip>

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

        <CustomTooltip title="Imprimer" arrow>
          <IconButton sx={ExtendedWhiteIconButtonStyle} onClick={handlePrint}>
            <FontAwesome icon={faPrint} width={18} />
          </IconButton>
        </CustomTooltip>

        <CalendarFilter
          onResetFilters={onResetFilters}
          onFilters={onFilters}
          initialColumns={initialColumns}
        />
      </Stack>

      {/* Second row - Date display */}
      <Box sx={secondRowStyle}>
        <FormControl size="small" sx={{ position: 'absolute', left: 32 }}>
          <Select
            value={view}
            onChange={(e) => onViewChange(e.target.value as CalendarViewType)}
            sx={viewSelectStyle}
            MenuProps={{ PaperProps: menuPaperProps }}
          >
            <MenuItem value="dayGridMonth">MOIS</MenuItem>
            <MenuItem value="timeGridWeek">SEMAINE</MenuItem>
            <MenuItem value="timeGridDay">JOUR</MenuItem>
          </Select>
        </FormControl>

        <Typography sx={dateDisplayStyle}>
          {getFormattedDate(date, view)}
        </Typography>

        <Box onClick={onCreateEvent} sx={createEventButtonStyle}>
        <CustomTooltip title={"Ajouter Un Nouveau rendez-vous"} arrow>
              <AddButton
                onClick={onCreateEvent}
                variant="contained"
                endIcon={<FontAwesome icon={faSquarePlus} width={18} />}
              >
                Nouveau événement
              </AddButton>
            </CustomTooltip>
        </Box>
      </Box>
      <Popover
        open={datePickerOpen}
        anchorEl={datePickerAnchor}
        onClose={handleDatePickerClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
      >
        <Box sx={{ p: 2 }}>
          <DatePicker
            label="Sélectionner une date"
            value={date}
            onChange={handleDatePickerChange}
            slotProps={{
              textField: {
                size: 'small',
                fullWidth: true,
              },
              actionBar: {
                actions: ['today', 'accept'],
              },
            }}
            sx={{ minWidth: 250 }}
          />
        </Box>
      </Popover>
    </Box>
  );
}
