import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import MenuItem from '@mui/material/MenuItem';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import LinearProgress from '@mui/material/LinearProgress';

import { useResponsive } from '@/hooks/use-responsive';

import { fDate } from '@/utils/format-time';

import Iconify from '@/shared/components/iconify';
import CustomPopover, { usePopover } from '@/shared/components/custom-popover';

import { ICalendarView } from '@/shared/types/calendar';
import { useBoolean } from '@/hooks';
import { ConfirmDialog } from '@/shared/components/custom-dialog';
import { exportCalendarByUserId, useImportCalendar } from '@/shared/api/calendar';
import { useRef } from 'react';


// ----------------------------------------------------------------------

const VIEW_OPTIONS = [
  {
    value: 'dayGridMonth',
    label: 'Month',
    icon: 'mingcute:calendar-month-line',
  },
  { value: 'timeGridWeek', label: 'Week', icon: 'mingcute:calendar-week-line' },
  { value: 'timeGridDay', label: 'Day', icon: 'mingcute:calendar-day-line' },
  {
    value: 'listWeek',
    label: 'Agenda',
    icon: 'fluent:calendar-agenda-24-regular',
  },
] as const;

// ----------------------------------------------------------------------

type Props = {
  date: Date;
  view: ICalendarView;
  loading: boolean;
  onToday: VoidFunction;
  onNextDate: VoidFunction;
  onPrevDate: VoidFunction;
  onOpenFilters: VoidFunction;
  onChangeView: (newView: ICalendarView) => void;
};

export default function CalendarToolbar({
  date,
  view,
  loading,
  onToday,
  onNextDate,
  onPrevDate,
  onChangeView,
  onOpenFilters,
}: Props) {
  const smUp = useResponsive('up', 'sm');
  const popover = usePopover();
  const popup = usePopover();
  const importCalendar = useBoolean();
  const exportCalendar = useBoolean();
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const selectedItem = VIEW_OPTIONS.find((item) => item.value === view) || VIEW_OPTIONS[0];

  return (
    <>
      <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{ p: 2.5, pr: 2, position: 'relative' }}>
        {smUp && (
          <Button
            size="small"
            color="inherit"
            onClick={(e) => {
              console.log("Month button clicked, popover.open:", popover.open);
              if (popover.open) {
                popover.onClose();
              } else {
                popover.onOpen(e);
              }
            }}
            startIcon={<Iconify icon={selectedItem.icon} />}
            endIcon={<Iconify icon="eva:arrow-ios-downward-fill" sx={{ ml: -0.5 }} />}
          >
            {selectedItem.label}
          </Button>
        )}

        {!smUp && (
          <IconButton onClick={popover.onOpen}>
            <Iconify icon={selectedItem.icon} />
          </IconButton>
        )}
        <CustomPopover open={popover.open} onClose={popover.onClose} arrow="top-left" sx={{ width: 140 }}>
          {VIEW_OPTIONS.map((option) => (
            <MenuItem
              key={option.value}
              selected={option.value === view}
              onClick={() => {
                console.log("Changing view to:", option.value);
                onChangeView(option.value);
                popover.onClose();
              }}
            >
              <Iconify icon={option.icon} sx={{ mr: 2 }} />
              {option.label}
            </MenuItem>
          ))}
        </CustomPopover>

        <Stack direction="row" alignItems="center" spacing={1}>
          <IconButton onClick={onPrevDate}>
            <Iconify icon="eva:arrow-ios-back-fill" />
          </IconButton>

          <Typography variant="h6">{fDate(date)}</Typography>

          <IconButton onClick={onNextDate}>
            <Iconify icon="eva:arrow-ios-forward-fill" />
          </IconButton>
        </Stack>

        <Stack direction="row" alignItems="center" spacing={1}>

          <Button size="small" color="error" variant="contained" onClick={onToday}>
            Today
          </Button>



          <IconButton onClick={onOpenFilters}>
            <Iconify icon="ic:round-filter-list" />
          </IconButton>
          <IconButton onClick={popup.onOpen}>
            <Iconify icon="eva:more-vertical-fill" />
          </IconButton>

          <CustomPopover open={popup.open} onClose={popup.onClose} arrow="top-left" sx={{ width: 140 }}>
            <MenuItem
              onClick={() => {
                popup.onClose();
                fileInputRef.current?.click();
              }}
            >
              <Iconify icon="solar:import-bold" />
              Import
            </MenuItem>

            <MenuItem
              onClick={() => {
                exportCalendar.onTrue();
                popup.onClose();
              }}
            >
              <Iconify icon="solar:export-bold" />
              Export
            </MenuItem>
          </CustomPopover>

          <input
            type="file"
            ref={fileInputRef}
            style={{ display: 'none' }}
            onChange={(e) => {
              if (e.target.files?.[0]) useImportCalendar(e.target.files[0]);
            }}
            accept=".csv,.ics"
          />
        </Stack>

        {loading && (
          <LinearProgress
            color="inherit"
            sx={{
              height: 2,
              width: 1,
              position: 'absolute',
              bottom: 0,
              left: 0,
            }}
          />
        )}
      </Stack>

      <ConfirmDialog
        open={exportCalendar.value}
        onClose={exportCalendar.onFalse}
        title="Export Calendar"
        content={
          <>
            Are you sure you want to export this calendar?
          </>
        }
        action={
          <Button
            variant="contained"
            color="primary"
            onClick={() => {
              exportCalendar.onFalse();
              exportCalendarByUserId();
            }}
          >
            Export
          </Button>
        }
      />
    </>
  );
}
