import * as React from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { updateVolunteerShift } from '@/services/volunteerShift.service';
import { zodResolver } from '@hookform/resolvers/zod';
import { Close, DeleteOutline } from '@mui/icons-material';
import { FormHelperText, IconButton, OutlinedInput, Stack, 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 Modal from '@mui/material/Modal';
import Select from '@mui/material/Select';
import MenuItem from '@mui/material/MenuItem';
import Typography from '@mui/material/Typography';
import { TimePicker } from '@mui/x-date-pickers';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);
import { enqueueSnackbar } from 'notistack';
import { Controller, useForm } from 'react-hook-form';
import { z as zod } from 'zod';

import { ISlot } from '@/types/slot.type';

const style = {
  position: 'absolute' as 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: '100%',
  maxWidth: { lg: '800px', md: '700px', sm: '500px', xs: '300px' },
  minWidth: { lg: '800px', md: '700px', sm: '500px', xs: '300px' },
  maxHeight: '90vh',
  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: 2, xs: 2 },
  overflowY: 'scroll',
  backdropFilter: 'blur(20px)',
  '&::-webkit-scrollbar': {
    width: '8px',
  },
  '&::-webkit-scrollbar-track': {
    background: (theme: any) => theme.palette.mode === 'dark' ? '#2d3748' : '#f1f5f9',
    borderRadius: '4px',
  },
  '&::-webkit-scrollbar-thumb': {
    background: (theme: any) => theme.palette.mode === 'dark' ? '#4a5568' : '#cbd5e0',
    borderRadius: '4px',
    '&:hover': {
      background: (theme: any) => theme.palette.mode === 'dark' ? '#718096' : '#a0aec0',
    },
  },
};

interface IEditShift {
  open: boolean;
  handleClose: () => void;
  slots: ISlot[];
  editingShift: any;
  refetch: () => void;
}

// Define the Zod schema for editing a shift
const EditShiftSchema = zod.object({
  shiftId: zod.string().min(1, 'Shift ID is required'),
  startTime: zod.string().min(1, 'Start time is required'),
  endTime: zod.string().min(1, 'End time is required'),
  slot: zod.string().min(1, 'Slot is required'),
  shiftDate: zod.coerce.date(),
  address: zod.string().optional().or(zod.literal('')),
});

export type EditShiftValues = zod.infer<typeof EditShiftSchema>;

export default function EditShiftModal({ open, handleClose, slots, editingShift, refetch }: IEditShift) {
  const [isLoading, setIsLoading] = React.useState(false);
  const theme = useTheme();

  const {
    control,
    handleSubmit,
    reset,
    watch,
    setValue,
    formState: { errors },
  } = useForm<EditShiftValues>({
    resolver: zodResolver(EditShiftSchema),
    defaultValues: {
      shiftId: '',
      shiftDate: new Date(),
      startTime: '',
      endTime: '',
      slot: '',
      address: '',
    },
  });

  // Update form values when editingShift changes
  React.useEffect(() => {
    if (editingShift) {
      console.log('EditShiftModal received shift data:', editingShift);
      
      const shiftId = editingShift._id || editingShift.id || editingShift.shiftId || '';
      const shiftDate = editingShift.date ? dayjs(editingShift.date, 'MM/DD/YYYY').toDate() : new Date();
      
      if (!shiftId) {
        console.warn('No valid shift ID found in editingShift:', editingShift);
      }

      // Helper function to convert UTC time to local time ISO format for display
      const convertToLocalISO = (timeValue: string | undefined, date: Date, isDisplayTime: boolean = false): string => {
        if (!timeValue) return '';
        
        // If it's already an ISO string (UTC), convert to local time
        if (dayjs(timeValue).isValid() && timeValue.includes('T')) {
          const parsedUTC = dayjs.utc(timeValue);
          if (parsedUTC.isValid()) {
            // Convert UTC to local time
            const localTime = parsedUTC.local();
            // Combine with the selected date to ensure correct date
            const dateObj = dayjs(date).startOf('day');
            const combined = dateObj
              .set('hour', localTime.hour())
              .set('minute', localTime.minute())
              .set('second', localTime.second());
            return combined.toISOString();
          }
        }
        
        // If it's a time-only string (HH:mm:ss), treat as UTC and convert to local
        if (/^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(timeValue)) {
          const [hours, minutes, seconds] = timeValue.split(':');
          // Create UTC datetime
          const dateObj = dayjs(date).startOf('day');
          const utcDateTime = dayjs.utc(`${dateObj.format('YYYY-MM-DD')} ${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds || '0').padStart(2, '0')}`);
          // Convert to local time
          const localTime = utcDateTime.local();
          const combined = dateObj
            .set('hour', localTime.hour())
            .set('minute', localTime.minute())
            .set('second', localTime.second());
          return combined.toISOString();
        }
        
        // If it's a display time (12-hour format), treat as UTC and convert to local
        if (isDisplayTime) {
          try {
            const [time, modifier] = timeValue.split(/([ap]m)/i);
            let [hours, minutes] = time.split(':');
            let hour24 = parseInt(hours, 10);
            if (hours === '12') {
              hour24 = 0;
            }
            if (modifier?.toLowerCase() === 'pm') {
              hour24 = hour24 + 12;
            }
            // Create UTC datetime
            const dateObj = dayjs(date).startOf('day');
            const utcDateTime = dayjs.utc(`${dateObj.format('YYYY-MM-DD')} ${String(hour24).padStart(2, '0')}:${String(minutes || '00').padStart(2, '0')}:00`);
            // Convert to local time
            const localTime = utcDateTime.local();
            const combined = dateObj
              .set('hour', localTime.hour())
              .set('minute', localTime.minute())
              .set('second', 0);
            return combined.toISOString();
          } catch (error) {
            console.error('Error converting time:', timeValue, error);
            return '';
          }
        }
        
        return '';
      };

      // Prefer shiftStartTime/shiftEndTime from backend if available
      // Convert UTC times to local time for display
      let startTimeISO = '';
      let endTimeISO = '';
      
      if (editingShift.shiftStartTime) {
        startTimeISO = convertToLocalISO(editingShift.shiftStartTime, shiftDate);
      } else if (editingShift.time) {
        const startTime = editingShift.time.split('-')[0]?.trim();
        startTimeISO = convertToLocalISO(startTime, shiftDate, true);
      }
      
      if (editingShift.shiftEndTime) {
        endTimeISO = convertToLocalISO(editingShift.shiftEndTime, shiftDate);
      } else if (editingShift.time) {
        const endTime = editingShift.time.split('-')[1]?.trim();
        endTimeISO = convertToLocalISO(endTime, shiftDate, true);
      }

      reset({
        shiftId: shiftId,
        shiftDate: shiftDate,
        startTime: startTimeISO,
        endTime: endTimeISO,
        slot: editingShift.slotId || '',
        address: editingShift.address || '',
      });
    }
  }, [editingShift, reset]);

  // Update time values when date changes (keep in local time)
  const selectedDate = watch('shiftDate');
  const startTime = watch('startTime');
  const endTime = watch('endTime');
  React.useEffect(() => {
    if (selectedDate && startTime) {
      const time = dayjs(startTime);
      if (time.isValid()) {
        const date = dayjs(selectedDate).startOf('day');
        const combinedDateTime = date
          .set('hour', time.hour())
          .set('minute', time.minute())
          .set('second', time.second());
        // Keep in local time
        const localDateTime = combinedDateTime.toISOString();
        setValue('startTime', localDateTime);
      }
    }
    if (selectedDate && endTime) {
      const time = dayjs(endTime);
      if (time.isValid()) {
        const date = dayjs(selectedDate).startOf('day');
        const combinedDateTime = date
          .set('hour', time.hour())
          .set('minute', time.minute())
          .set('second', time.second());
        // Keep in local time
        const localDateTime = combinedDateTime.toISOString();
        setValue('endTime', localDateTime);
      }
    }
  }, [selectedDate, startTime, endTime, setValue]);

  const onSubmit = React.useCallback(async (values: EditShiftValues) => {
    try {
      setIsLoading(true);
      
      console.log('Submitting shift data:', values);
      
      // Check if we have a valid shift ID
      if (!values.shiftId || values.shiftId.trim() === '') {
        enqueueSnackbar('Cannot update shift: Invalid shift ID', { variant: 'error' });
        setIsLoading(false);
        return;
      }
      
      // Convert local time back to UTC for API
      const convertLocalToUTC = (localISO: string): string => {
        if (!localISO) return localISO;
        const localTime = dayjs(localISO);
        if (localTime.isValid()) {
          return localTime.utc().toISOString();
        }
        return localISO;
      };

      const updateData = {
        shiftId: values.shiftId,
        shiftDate: dayjs(values.shiftDate).format('YYYY-MM-DD'),
        shiftStartTime: convertLocalToUTC(values.startTime), // Convert local to UTC
        shiftEndTime: convertLocalToUTC(values.endTime), // Convert local to UTC
        slotId: values.slot,
        address: values.address,
      };
      
      console.log('Update data being sent:', updateData);

      await updateVolunteerShift(updateData);
      
      enqueueSnackbar('Volunteer shift updated successfully', { variant: 'success' });
      setIsLoading(false);
      reset();
      refetch();
      handleClose();
    } catch (error: any) {
      console.error('Error updating volunteer shift:', error);
      const errorMessage = error.response?.data?.message || error.message || 'Error updating volunteer shift';
      enqueueSnackbar(errorMessage, { variant: 'error' });
      setIsLoading(false);
    }
  }, [reset, refetch, handleClose]);

  if (!editingShift) return null;

  return (
    <div>
      <Modal
        aria-labelledby="edit-shift-modal-title"
        aria-describedby="edit-shift-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: '800px', md: '700px', sm: '500px', xs: '300px' },
              minWidth: { lg: '800px', md: '700px', sm: '500px', xs: '300px' },
              minHeight: 'auto',
              maxHeight: '90vh',
            }}
          >
            <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: 3 }}>
                <Typography 
                  id="edit-shift-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',
                  }}
                >
                  ✏️ Edit Shift
                </Typography>
              </Stack>

              <Box>
                <form onSubmit={handleSubmit(onSubmit)}>
                  <Stack spacing={3} mt={2}>
                    {/* Date Selection */}
                    <Stack spacing={1}>
                      <Controller
                        control={control}
                        name="shiftDate"
                        render={({ field }) => (
                          <DatePicker
                            label="Shift Date"
                            value={field.value ? dayjs(field.value) : null}
                            onChange={(newValue) => field.onChange(newValue)}
                            minDate={dayjs()}
                            slotProps={{
                              textField: {
                                error: Boolean(errors.shiftDate),
                                helperText: errors.shiftDate?.message,
                                fullWidth: true,
                              },
                            }}
                          />
                        )}
                      />
                    </Stack>

                    {/* Time Selection */}
                    <Stack direction="row" spacing={2}>
                      <Controller
                        name="startTime"
                        control={control}
                        render={({ field }) => {
                          const selectedDate = watch('shiftDate');
                          return (
                            <FormControl error={Boolean(errors.startTime)} fullWidth>
                              <TimePicker
                                label="Start Time"
                                value={field.value ? dayjs(field.value) : null}
                                onChange={(newTime) => {
                                  if (newTime && selectedDate) {
                                    const date = dayjs(selectedDate).startOf('day');
                                    const combinedDateTime = date
                                      .set('hour', newTime.hour())
                                      .set('minute', newTime.minute())
                                      .set('second', newTime.second());
                                    // Store as local time (will be converted to UTC on submit)
                                    const localDateTime = combinedDateTime.toISOString();
                                    field.onChange(localDateTime);
                                  } else {
                                    field.onChange('');
                                  }
                                }}
                                slotProps={{
                                  textField: {
                                    error: Boolean(errors.startTime),
                                    helperText: errors.startTime?.message,
                                    fullWidth: true,
                                  },
                                }}
                              />
                            </FormControl>
                          );
                        }}
                      />

                      <Controller
                        name="endTime"
                        control={control}
                        render={({ field }) => {
                          const selectedDate = watch('shiftDate');
                          return (
                            <FormControl error={Boolean(errors.endTime)} fullWidth>
                              <TimePicker
                                label="End Time"
                                value={field.value ? dayjs(field.value) : null}
                                onChange={(newTime) => {
                                  if (newTime && selectedDate) {
                                    const date = dayjs(selectedDate).startOf('day');
                                    const combinedDateTime = date
                                      .set('hour', newTime.hour())
                                      .set('minute', newTime.minute())
                                      .set('second', newTime.second());
                                    // Store as local time (will be converted to UTC on submit)
                                    const localDateTime = combinedDateTime.toISOString();
                                    field.onChange(localDateTime);
                                  } else {
                                    field.onChange('');
                                  }
                                }}
                                slotProps={{
                                  textField: {
                                    error: Boolean(errors.endTime),
                                    helperText: errors.endTime?.message,
                                    fullWidth: true,
                                  },
                                }}
                              />
                            </FormControl>
                          );
                        }}
                      />
                    </Stack>

                    {/* Slot Selection */}
                    <Controller
                      name="slot"
                      control={control}
                      render={({ field }) => (
                        <FormControl error={Boolean(errors.slot)} fullWidth>
                          <InputLabel>Volunteer Slot</InputLabel>
                          <Select
                            {...field}
                            label="Volunteer Slot"
                          >
                            {slots.map((slot, index) => (
                              <MenuItem key={index} value={slot._id}>
                                {slot.slotName} - {slot.numberOfSlots} slots
                              </MenuItem>
                            ))}
                          </Select>
                          {errors.slot && (
                            <FormHelperText>{errors.slot.message}</FormHelperText>
                          )}
                        </FormControl>
                      )}
                    />

                    {/* Address */}
                    <Controller
                      name="address"
                      control={control}
                      render={({ field }) => (
                        <FormControl error={Boolean(errors.address)} fullWidth>
                          <InputLabel>Location/Address</InputLabel>
                          <OutlinedInput 
                            {...field} 
                            label="Location/Address" 
                            multiline
                            rows={2}
                          />
                          {errors.address && (
                            <FormHelperText>{errors.address.message}</FormHelperText>
                          )}
                        </FormControl>
                      )}
                    />

                    {/* Action Buttons */}
                    <Stack direction="row" spacing={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 ? 'Updating...' : '💾 Update Shift'}
                      </Button>
                      
                      <Button 
                        variant="text" 
                        onClick={handleClose}
                        disabled={isLoading}
                        size="large"
                        sx={{
                          minWidth: 100,
                          height: 48,
                          borderRadius: 3,
                          color: theme.palette.mode === 'dark' ? '#a0aec0' : '#64748b',
                          fontWeight: 500,
                          textTransform: 'none',
                          fontSize: '1rem',
                          '&:hover': {
                            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>
  );
}
