import * as React from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { createVolunteerSlot } from '@/services/volunteerSlot.service';
import { zodResolver } from '@hookform/resolvers/zod';
import { Close, DeleteOutline, Remove } from '@mui/icons-material';
import { Autocomplete, FormHelperText, IconButton, OutlinedInput, Stack, TextField, useTheme } from '@mui/material';
import Backdrop from '@mui/material/Backdrop';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Fade from '@mui/material/Fade';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import ListSubheader from '@mui/material/ListSubheader';
import MenuItem from '@mui/material/MenuItem';
import Modal from '@mui/material/Modal';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import Typography from '@mui/material/Typography';
import { TimePicker } from '@mui/x-date-pickers';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { Minus, MinusCircle, Plus } from '@phosphor-icons/react/dist/ssr';
import { AxiosError } from 'axios';
import dayjs from 'dayjs';
import { enqueueSnackbar } from 'notistack';
import { Controller, useFieldArray, useForm } from 'react-hook-form';
import { z as zod } from 'zod';

const style = {
  position: 'absolute' as 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: '100%',
  maxWidth: { lg: '600px', md: '550px', sm: '500px', xs: '300px' },
  minWidth: { lg: '600px', md: '550px', sm: '500px', xs: '300px' },
  maxHeight: '70vh',
  minHeight: 'auto',
  bgcolor: 'background.paper',
  border: (theme: any) => theme.palette.mode === 'dark' 
    ? '1px solid rgba(255, 255, 255, 0.12)' 
    : '1px solid rgba(0, 0, 0, 0.12)',
  borderRadius: 4,
  boxShadow: (theme: any) => theme.palette.mode === 'dark' 
    ? '0 24px 48px rgba(0, 0, 0, 0.4), 0 8px 16px rgba(0, 0, 0, 0.2)' 
    : '0 24px 48px rgba(0, 0, 0, 0.15), 0 8px 16px rgba(0, 0, 0, 0.1)',
  background: (theme: any) => theme.palette.mode === 'dark' 
    ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
    : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
  p: { lg: 4, md: 4, sm: 3, xs: 2 },
  overflowY: 'auto',
  backdropFilter: 'blur(20px)',
};

interface IAddSlot {
  open: boolean;
  handleClose: () => void;
}
type TimeSlot = {
  startTime: string;
  endTime: string;
  location: string;
};

const dummyData = [
  { label: 'The Shawshank Redemption', value: 1994 },
  { label: 'The Godfather', value: 1972 },
  { label: 'The Godfather: Part II', value: 1974 },
  { label: 'The Dark Knight', value: 2008 },
];

const schema = zod.object({
  organizerName: zod.string().min(1, 'Slot is required'),
  numberOfSeats: zod.string().min(1, 'Number of seats is required'),
});

export type CreateSlotValues = zod.infer<typeof schema>;

export default function AddSlotModal({ open, handleClose }: IAddSlot) {
  const [isLoading, setIsLoading] = React.useState(false);
  const pathname = usePathname();
  const theme = useTheme();
  const {
    control,
    handleSubmit,
    setError,
    reset,
    formState: { errors },
  } = useForm<CreateSlotValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      numberOfSeats: '1',
      organizerName: '',
    },
  });

  const router = useRouter();
  const searchParams = useSearchParams();

  const closeSlotModal = () => {
    // Remove the `modal` query param while preserving dynamic path
    router.replace(`?modal=1`); // Remove the `modal` query param from the route
  };

  const onSubmit = React.useCallback(async (values: CreateSlotValues) => {
    console.log(values, 'Vallues');
    try {
      setIsLoading(true);
      const response = await createVolunteerSlot({
        numberOfSlots: parseInt(values.numberOfSeats),
        slotName: values.organizerName,
      });
      console.log(response, 'Response notification');
      enqueueSnackbar('Volunteer slot added successfully', { variant: 'success' });
      setIsLoading(false);
      closeSlotModal();
    } catch (error) {
      console.error('Error in creating volunteer slot:', error);
      enqueueSnackbar('Error in creating volunteer slot', { variant: 'error' });
      setIsLoading(false);
    }
  }, []);

  return (
    <div>
      <Modal
        aria-labelledby="transition-modal-title"
        aria-describedby="transition-modal-description"
        open={open}
        onClose={handleClose}
        closeAfterTransition
        slots={{ backdrop: Backdrop }}
        slotProps={{
          backdrop: {
            timeout: 200,
          },
        }}
        style={{ 
          backdropFilter: 'blur(12px)', 
          backgroundColor: theme.palette.mode === 'dark' 
            ? 'rgba(0, 0, 0, 0.7)' 
            : 'rgba(0, 0, 0, 0.5)', 
          outline: 0 
        }}
      >
        <Fade in={open}>
          <Box
            sx={{
              position: 'absolute' as 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: '100%',
              maxWidth: { lg: '1060px', md: '850px', sm: '500px', xs: '300px' },
              minWidth: { lg: '1060px', md: '850px', sm: '500px', xs: '300px' },
              minHeight: '100vh',
              maxHeight: '100vh',
            }}
          >
            <Box sx={style}>
              <IconButton
                onClick={handleClose}
                sx={{
                  position: 'absolute',
                  right: 16,
                  top: 16,
                  backgroundColor: theme.palette.mode === 'dark' 
                    ? 'rgba(255, 255, 255, 0.08)' 
                    : 'rgba(0, 0, 0, 0.04)',
                  color: theme.palette.mode === 'dark' ? '#e2e8f0' : '#64748b',
                  width: 40,
                  height: 40,
                  '&:hover': {
                    backgroundColor: theme.palette.mode === 'dark' 
                      ? 'rgba(239, 68, 68, 0.2)' 
                      : 'rgba(239, 68, 68, 0.1)',
                    color: theme.palette.mode === 'dark' ? '#f87171' : '#dc2626',
                    transform: 'scale(1.05)',
                  },
                  transition: 'all 0.2s ease-in-out',
                  backdropFilter: 'blur(8px)',
                  border: theme.palette.mode === 'dark' 
                    ? '1px solid rgba(255, 255, 255, 0.08)' 
                    : '1px solid rgba(0, 0, 0, 0.08)',
                }}
              >
                <Close />
              </IconButton>
              <Stack direction={'row'} justifyContent={'space-between'} sx={{ mb: 4 }}>
                <Typography 
                  id="transition-modal-title" 
                  variant="h4" 
                  component="h2"
                  sx={{
                    fontWeight: 700,
                    background: theme.palette.mode === 'dark' 
                      ? 'linear-gradient(135deg, #ffd700 0%, #ffed4a 100%)' 
                      : 'linear-gradient(135deg, #1a202c 0%, #2d3748 100%)',
                    WebkitBackgroundClip: 'text',
                    WebkitTextFillColor: 'transparent',
                    backgroundClip: 'text',
                    letterSpacing: '-0.025em',
                  }}
                >
                  🎯 Add New Slot
                </Typography>
              </Stack>
              <Box>
                <form onSubmit={handleSubmit(onSubmit)}>
                  <Stack spacing={2} mt={2}>
                    <Stack direction="row" spacing={2} mb={2}>
                      <Stack>
                        <Controller
                          name={'organizerName'}
                          control={control}
                          render={({ field }) => (
                            <FormControl error={Boolean(errors.organizerName)} fullWidth>
                              <InputLabel>Slot Name</InputLabel>
                              <OutlinedInput {...field} label="Slot Name" />
                              {errors.organizerName && <FormHelperText>{errors.organizerName.message}</FormHelperText>}
                            </FormControl>
                          )}
                        />
                      </Stack>
                      <Stack>
                        <Controller
                          name={'numberOfSeats'}
                          control={control}
                          render={({ field }) => (
                            <FormControl error={Boolean(errors.numberOfSeats)} fullWidth>
                              <InputLabel>Number of seats</InputLabel>
                              <OutlinedInput {...field} label="Number of seats" type="number" />
                              {errors.numberOfSeats && <FormHelperText>{errors.numberOfSeats.message}</FormHelperText>}
                            </FormControl>
                          )}
                        />
                      </Stack>
                    </Stack>

                    <Stack direction={'row'} gap={2} sx={{ mt: 4, pt: 3, borderTop: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #e2e8f0' }}>
                      <Button 
                        variant="contained" 
                        type="submit" 
                        disabled={isLoading}
                        size="large"
                        sx={{
                          minWidth: 120,
                          height: 48,
                          borderRadius: 3,
                          background: theme.palette.mode === 'dark' 
                            ? 'linear-gradient(135deg, #ffd700 0%, #ffed4a 100%)' 
                            : 'linear-gradient(135deg, #1a202c 0%, #2d3748 100%)',
                          color: theme.palette.mode === 'dark' ? '#1a202c' : '#ffffff',
                          fontWeight: 600,
                          textTransform: 'none',
                          fontSize: '1rem',
                          '&:hover': {
                            background: theme.palette.mode === 'dark' 
                              ? 'linear-gradient(135deg, #ffed4a 0%, #ffd700 100%)' 
                              : 'linear-gradient(135deg, #2d3748 0%, #4a5568 100%)',
                            transform: 'translateY(-2px)',
                            boxShadow: theme.palette.mode === 'dark' 
                              ? '0 8px 25px rgba(255, 215, 0, 0.3)' 
                              : '0 8px 25px rgba(26, 32, 44, 0.3)',
                          },
                          '&:disabled': {
                            background: theme.palette.mode === 'dark' ? '#4a5568' : '#e2e8f0',
                            color: theme.palette.mode === 'dark' ? '#a0aec0' : '#9ca3af',
                          },
                          transition: 'all 0.2s ease-in-out',
                          boxShadow: theme.palette.mode === 'dark' 
                            ? '0 4px 12px rgba(255, 215, 0, 0.2)' 
                            : '0 4px 12px rgba(26, 32, 44, 0.2)',
                        }}
                      >
                        {isLoading ? 'Creating...' : '✨ Create Slot'}
                      </Button>
                      <Button 
                        variant="outlined" 
                        onClick={handleClose}
                        size="large"
                        sx={{
                          minWidth: 100,
                          height: 48,
                          borderRadius: 3,
                          border: theme.palette.mode === 'dark' ? '2px solid #4a5568' : '2px solid #e2e8f0',
                          color: theme.palette.mode === 'dark' ? '#a0aec0' : '#64748b',
                          fontWeight: 500,
                          textTransform: 'none',
                          fontSize: '1rem',
                          '&:hover': {
                            border: theme.palette.mode === 'dark' ? '2px solid #718096' : '2px solid #cbd5e0',
                            backgroundColor: theme.palette.mode === 'dark' 
                              ? 'rgba(113, 128, 150, 0.1)' 
                              : 'rgba(203, 213, 224, 0.1)',
                            transform: 'translateY(-1px)',
                          },
                          transition: 'all 0.2s ease-in-out',
                        }}
                      >
                        Cancel
                      </Button>
                    </Stack>
                  </Stack>
                </form>
              </Box>
            </Box>
          </Box>
        </Fade>
      </Modal>
    </div>
  );
}
