'use client';

import React, { useCallback, useEffect, useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Stack,
  Typography,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormControlLabel,
  Switch,
  Tab,
  Tabs,
  Box,
  Chip,
  Autocomplete,
  Alert,
  IconButton,
} from '@mui/material';
import { DatePicker } from '@mui/x-date-pickers';
import CloseIcon from '@mui/icons-material/Close';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import PersonIcon from '@mui/icons-material/Person';
import VolunteerActivismIcon from '@mui/icons-material/VolunteerActivism';
import EmailIcon from '@mui/icons-material/Email';
import PhoneIcon from '@mui/icons-material/Phone';
import BadgeIcon from '@mui/icons-material/Badge';
import WcIcon from '@mui/icons-material/Wc';
import CakeIcon from '@mui/icons-material/Cake';
import ContactPhoneIcon from '@mui/icons-material/ContactPhone';
import StarIcon from '@mui/icons-material/Star';
import InterestsIcon from '@mui/icons-material/Interests';
import NotificationsIcon from '@mui/icons-material/Notifications';
import dayjs, { Dayjs } from 'dayjs';
import { enqueueSnackbar } from 'notistack';
import { updateUserInfo, updateVolunteerInfo, fetchSingleUser } from '@/services/user.service';
import { AppLoader } from '@/components/core/app-loader';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`edit-tabpanel-${index}`}
      aria-labelledby={`edit-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
    </div>
  );
}

function a11yProps(index: number) {
  return {
    id: `edit-tab-${index}`,
    'aria-controls': `edit-tabpanel-${index}`,
  };
}

interface UserData {
  _id: string;
  fullName: string;
  emailAddress: string;
  phoneNumber: string;
  gender?: string;
  dateOfBirth?: string;
  address?: string;
  country?: string;
  state?: string;
  city?: string;
  isEmailSubscribed?: boolean;
  isPhoneSubscribed?: boolean;
}

interface VolunteerData {
  _id: string;
  firstName: string;
  lastName: string;
  emailAddress: string;
  phoneNumber: string;
  address?: string;
  preferedMethodOfcontact?: 'phoneNumber' | 'emailAddress';
  goodAt?: string;
  interest?: string | string[];
  hearFrom?: string;
  status?: 'pending' | 'accepted' | 'rejected' | 'deleted';
  isEmailSubscribed?: boolean;
  isPhoneSubscribed?: boolean;
}

interface EditUserModalProps {
  open: boolean;
  onClose: () => void;
  userId: string;
  onUpdate: () => void;
}

const genderOptions = ['Male', 'Female', 'Other'];
const volunteerStatusOptions = ['pending', 'accepted', 'rejected'];
const contactMethodOptions = [
  { value: 'phoneNumber', label: 'Phone Number' },
  { value: 'emailAddress', label: 'Email Address' }
];

const commonInterests = [
  'Education', 'Healthcare', 'Environment', 'Youth Development', 
  'Elderly Care', 'Community Service', 'Event Planning', 'Fundraising',
  'Social Media', 'Technology', 'Art & Creativity', 'Sports & Fitness'
];

const EditUserModal: React.FC<EditUserModalProps> = ({ open, onClose, userId, onUpdate }) => {
  const [tabValue, setTabValue] = useState(0);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [userData, setUserData] = useState<UserData | null>(null);
  const [volunteerData, setVolunteerData] = useState<VolunteerData | null>(null);
  const [dateOfBirth, setDateOfBirth] = useState<Dayjs | null>(null);
  const [interests, setInterests] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);

  // Fetch user data when modal opens
  const fetchUserData = useCallback(async () => {
    if (!open || !userId) return;
    
    try {
      setLoading(true);
      setError(null);
      const response = await fetchSingleUser(userId);
      const userDetail = response.data.data.userDetail[0];
      const volunteerDetail = response.data.data.volunteerDetail[0];
      
      if (userDetail) {
        setUserData({
          _id: userDetail._id,
          fullName: userDetail.fullName || '',
          emailAddress: userDetail.emailAddress || '',
          phoneNumber: userDetail.phoneNumber || '',
          gender: userDetail.gender || '',
          dateOfBirth: userDetail.dateOfBirth || '',
          address: userDetail.address || '',
          country: userDetail.country || '',
          state: userDetail.state || '',
          city: userDetail.city || '',
          isEmailSubscribed: userDetail.isEmailSubscribed || false,
          isPhoneSubscribed: userDetail.isPhoneSubscribed || false,
        });
        
        if (userDetail.dateOfBirth) {
          setDateOfBirth(dayjs(userDetail.dateOfBirth));
        }
      }

      if (volunteerDetail) {
        setVolunteerData({
          _id: volunteerDetail._id,
          firstName: volunteerDetail.firstName || '',
          lastName: volunteerDetail.lastName || '',
          emailAddress: volunteerDetail.emailAddress || '',
          phoneNumber: volunteerDetail.phoneNumber || '',
          address: volunteerDetail.address || '',
          preferedMethodOfcontact: volunteerDetail.preferedMethodOfcontact || 'emailAddress',
          goodAt: volunteerDetail.goodAt || '',
          interest: volunteerDetail.interest || [],
          hearFrom: volunteerDetail.hearFrom || '',
          status: volunteerDetail.status || 'pending',
          isEmailSubscribed: volunteerDetail.isEmailSubscribed || false,
          isPhoneSubscribed: volunteerDetail.isPhoneSubscribed || false,
        });

        // Handle interests array
        if (volunteerDetail.interest) {
          if (Array.isArray(volunteerDetail.interest)) {
            setInterests(volunteerDetail.interest);
          } else if (typeof volunteerDetail.interest === 'string') {
            setInterests([volunteerDetail.interest]);
          }
        }
      }
    } catch (error: any) {
      console.error('Error fetching user data:', error);
      setError('Failed to load user data. Please try again.');
      enqueueSnackbar('Failed to load user data', { variant: 'error' });
    } finally {
      setLoading(false);
    }
  }, [open, userId]);

  useEffect(() => {
    fetchUserData();
  }, [fetchUserData]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  const handleUserDataChange = (field: keyof UserData, value: any) => {
    setUserData(prev => prev ? { ...prev, [field]: value } : null);
  };

  const handleVolunteerDataChange = (field: keyof VolunteerData, value: any) => {
    setVolunteerData(prev => prev ? { ...prev, [field]: value } : null);
  };

  const handleDateChange = (date: Dayjs | null) => {
    setDateOfBirth(date);
    if (date) {
      handleUserDataChange('dateOfBirth', date.format('MMMM D, YYYY'));
    }
  };

  const handleInterestsChange = (event: any, newValue: string[]) => {
    setInterests(newValue);
    handleVolunteerDataChange('interest', newValue);
  };

  const handleSaveUser = async () => {
    if (!userData) return;

    try {
      setSaving(true);
      setError(null);

      const updateData = {
        fullName: userData.fullName,
        emailAddress: userData.emailAddress,
        phoneNumber: userData.phoneNumber,
        gender: userData.gender,
        dateOfBirth: userData.dateOfBirth,
      };

      await updateUserInfo(userId, updateData);
      enqueueSnackbar('User information updated successfully', { variant: 'success' });
      onUpdate();
    } catch (error: any) {
      console.error('Error updating user:', error);
      const errorMessage = error.response?.data?.message || 'Failed to update user information';
      setError(errorMessage);
      enqueueSnackbar(errorMessage, { variant: 'error' });
    } finally {
      setSaving(false);
    }
  };

  const handleSaveVolunteer = async () => {
    if (!volunteerData) return;

    try {
      setSaving(true);
      setError(null);

      const updateData = {
        firstName: volunteerData.firstName,
        lastName: volunteerData.lastName,
        emailAddress: volunteerData.emailAddress,
        phoneNumber: volunteerData.phoneNumber,
        preferedMethodOfcontact: volunteerData.preferedMethodOfcontact,
        goodAt: volunteerData.goodAt,
        interest: interests,
        isEmailSubscribed: volunteerData.isEmailSubscribed,
        isPhoneSubscribed: volunteerData.isPhoneSubscribed,
      };

      await updateVolunteerInfo(volunteerData._id, updateData);
      enqueueSnackbar('Volunteer information updated successfully', { variant: 'success' });
      onUpdate();
    } catch (error: any) {
      console.error('Error updating volunteer:', error);
      const errorMessage = error.response?.data?.message || 'Failed to update volunteer information';
      setError(errorMessage);
      enqueueSnackbar(errorMessage, { variant: 'error' });
    } finally {
      setSaving(false);
    }
  };

  const handleClose = () => {
    setTabValue(0);
    setError(null);
    onClose();
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="md"
      fullWidth
      PaperProps={{
        sx: { 
          minHeight: '700px',
          borderRadius: 3,
          background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
          overflow: 'hidden'
        }
      }}
    >
      <DialogTitle sx={{ 
        background: 'rgba(255, 255, 255, 0.95)',
        backdropFilter: 'blur(10px)',
        borderBottom: '1px solid rgba(255, 255, 255, 0.2)',
        p: 3,
        pb: 2
      }}>
        <Stack direction="row" justifyContent="space-between" alignItems="center">
          <Stack direction="row" alignItems="center" spacing={2.5}>
            <Box sx={{ 
              p: 1.5,
              borderRadius: 2,
              background: 'linear-gradient(135deg, #667eea, #764ba2)',
              color: 'white',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: 48,
              height: 48,
              boxShadow: '0 4px 10px rgba(102, 126, 234, 0.2)'
            }}>
              <EditIcon fontSize="medium" />
            </Box>
            <Box>
              <Typography variant="h5" fontWeight="700" color="text.primary" sx={{ mb: 0.5 }}>
                Edit User Information
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Update user details and preferences
              </Typography>
            </Box>
          </Stack>
          <IconButton 
            onClick={handleClose}
            sx={{ 
              bgcolor: 'rgba(0,0,0,0.04)',
              '&:hover': { bgcolor: 'rgba(0,0,0,0.08)' },
              width: 42,
              height: 42
            }}
          >
            <CloseIcon />
          </IconButton>
        </Stack>
      </DialogTitle>

      {error && (
        <Box sx={{ px: 3, py: 2, background: 'rgba(255, 255, 255, 0.95)' }}>
          <Alert 
            severity="error" 
            onClose={() => setError(null)}
            sx={{ borderRadius: 2 }}
          >
            {error}
          </Alert>
        </Box>
      )}

      <Box sx={{ 
        background: 'rgba(255, 255, 255, 0.95)',
        backdropFilter: 'blur(10px)',
        borderBottom: '1px solid rgba(255, 255, 255, 0.2)'
      }}>
        <Box sx={{ px: 3, pt: 2 }}>
          <Tabs
            value={tabValue}
            onChange={handleTabChange}
            aria-label="edit user tabs"
            variant="fullWidth"
            sx={{
              '& .MuiTab-root': {
                minHeight: 80,
                fontWeight: 600,
                fontSize: '1rem',
                textTransform: 'none',
                borderRadius: '12px 12px 0 0',
                mx: 0.5,
                transition: 'all 0.3s ease-in-out',
                position: 'relative',
                '&:before': {
                  content: '""',
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  borderRadius: '12px 12px 0 0',
                  background: 'transparent',
                  transition: 'all 0.3s ease-in-out',
                  zIndex: -1
                },
                '&:hover': {
                  color: '#667eea',
                  '&:before': {
                    background: 'rgba(102, 126, 234, 0.08)'
                  }
                },
                '&.Mui-selected': {
                  color: '#667eea',
                  fontWeight: 700,
                  '&:before': {
                    background: 'linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1))',
                    border: '2px solid rgba(102, 126, 234, 0.2)',
                    borderBottom: 'none'
                  }
                },
                '&.Mui-disabled': {
                  color: 'rgba(0, 0, 0, 0.26)',
                  opacity: 0.5
                },
                '& .MuiTab-iconWrapper': {
                  marginBottom: '4px !important',
                  marginRight: '8px !important'
                }
              },
              '& .MuiTabs-indicator': {
                display: 'none'
              },
              '& .MuiTabs-flexContainer': {
                gap: 1
              }
            }}
          >
            <Tab 
              icon={
                <Box sx={{
                  p: 1,
                  borderRadius: 1.5,
                  background: tabValue === 0 ? 'linear-gradient(135deg, #667eea, #764ba2)' : 'rgba(102, 126, 234, 0.1)',
                  color: tabValue === 0 ? 'white' : '#667eea',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  transition: 'all 0.3s ease-in-out'
                }}>
                  <PersonIcon fontSize="small" />
                </Box>
              } 
              iconPosition="start"
              label="User Information" 
              {...a11yProps(0)} 
            />
            <Tab 
              icon={
                <Box sx={{
                  p: 1,
                  borderRadius: 1.5,
                  background: tabValue === 1 ? 'linear-gradient(135deg, #667eea, #764ba2)' : 'rgba(102, 126, 234, 0.1)',
                  color: tabValue === 1 ? 'white' : '#667eea',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  transition: 'all 0.3s ease-in-out',
                  opacity: !volunteerData ? 0.5 : 1
                }}>
                  <VolunteerActivismIcon fontSize="small" />
                </Box>
              } 
              iconPosition="start"
              label="Volunteer Information" 
              {...a11yProps(1)} 
              disabled={!volunteerData}
            />
          </Tabs>
        </Box>
      </Box>

      <DialogContent sx={{ 
        p: 0,
        position: 'relative',
        minHeight: 400,
        background: 'rgba(255, 255, 255, 0.95)',
        backdropFilter: 'blur(10px)'
      }}>
        {loading && <AppLoader fill size="lg" />}
        {!loading && (
          <>
            <TabPanel value={tabValue} index={0}>
              {userData && (
                <Stack spacing={4}>
                  <Typography variant="h6" color="text.primary" fontWeight="600" sx={{ mb: 2 }}>
                    👤 Personal Information
                  </Typography>
                  
                  <TextField
                    fullWidth
                    label="Full Name"
                    value={userData.fullName}
                    onChange={(e) => handleUserDataChange('fullName', e.target.value)}
                    required
                    InputProps={{
                      startAdornment: <BadgeIcon sx={{ color: '#667eea', mr: 1 }} />,
                    }}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        borderRadius: 2,
                        '&:hover fieldset': {
                          borderColor: '#667eea',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: '#667eea',
                        }
                      }
                    }}
                  />
                  
                  <TextField
                    fullWidth
                    label="Email Address"
                    type="email"
                    value={userData.emailAddress}
                    onChange={(e) => handleUserDataChange('emailAddress', e.target.value)}
                    required
                    InputProps={{
                      startAdornment: <EmailIcon sx={{ color: '#667eea', mr: 1 }} />,
                    }}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        borderRadius: 2,
                        '&:hover fieldset': {
                          borderColor: '#667eea',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: '#667eea',
                        }
                      }
                    }}
                  />
                  
                  <TextField
                    fullWidth
                    label="Phone Number"
                    value={userData.phoneNumber}
                    onChange={(e) => handleUserDataChange('phoneNumber', e.target.value)}
                    required
                    InputProps={{
                      startAdornment: <PhoneIcon sx={{ color: '#667eea', mr: 1 }} />,
                    }}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        borderRadius: 2,
                        '&:hover fieldset': {
                          borderColor: '#667eea',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: '#667eea',
                        }
                      }
                    }}
                  />
                  
                  <FormControl fullWidth sx={{
                    '& .MuiOutlinedInput-root': {
                      borderRadius: 2,
                      '&:hover fieldset': {
                        borderColor: '#667eea',
                      },
                      '&.Mui-focused fieldset': {
                        borderColor: '#667eea',
                      }
                    }
                  }}>
                    <InputLabel>Gender</InputLabel>
                    <Select
                      value={userData.gender || ''}
                      label="Gender"
                      onChange={(e) => handleUserDataChange('gender', e.target.value)}
                      startAdornment={<WcIcon sx={{ color: '#667eea', mr: 1, ml: 1 }} />}
                    >
                      {genderOptions.map((option) => (
                        <MenuItem key={option} value={option}>
                          {option}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                  
                  <DatePicker
                    label="Date of Birth"
                    value={dateOfBirth}
                    onChange={handleDateChange}
                    slotProps={{
                      textField: {
                        fullWidth: true,
                        InputProps: {
                          startAdornment: <CakeIcon sx={{ color: '#667eea', mr: 1 }} />,
                        },
                        sx: {
                          '& .MuiOutlinedInput-root': {
                            borderRadius: 2,
                            '&:hover fieldset': {
                              borderColor: '#667eea',
                            },
                            '&.Mui-focused fieldset': {
                              borderColor: '#667eea',
                            }
                          }
                        }
                      }
                    }}
                  />
                </Stack>
              )}
            </TabPanel>

            <TabPanel value={tabValue} index={1}>
              {volunteerData && (
                <Stack spacing={4}>
                  <Typography variant="h6" color="text.primary" fontWeight="600" sx={{ mb: 2 }}>
                    🤝 Volunteer Details
                  </Typography>
                  
                  <Stack direction="row" spacing={2}>
                    <TextField
                      fullWidth
                      label="First Name"
                      value={volunteerData.firstName}
                      onChange={(e) => handleVolunteerDataChange('firstName', e.target.value)}
                      required
                      InputProps={{
                        startAdornment: <BadgeIcon sx={{ color: '#667eea', mr: 1 }} />,
                      }}
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          borderRadius: 2,
                          '&:hover fieldset': {
                            borderColor: '#667eea',
                          },
                          '&.Mui-focused fieldset': {
                            borderColor: '#667eea',
                          }
                        }
                      }}
                    />
                    
                    <TextField
                      fullWidth
                      label="Last Name"
                      value={volunteerData.lastName}
                      onChange={(e) => handleVolunteerDataChange('lastName', e.target.value)}
                      required
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          borderRadius: 2,
                          '&:hover fieldset': {
                            borderColor: '#667eea',
                          },
                          '&.Mui-focused fieldset': {
                            borderColor: '#667eea',
                          }
                        }
                      }}
                    />
                  </Stack>
                  
                  <TextField
                    fullWidth
                    label="Email Address"
                    type="email"
                    value={volunteerData.emailAddress}
                    onChange={(e) => handleVolunteerDataChange('emailAddress', e.target.value)}
                    required
                    InputProps={{
                      startAdornment: <EmailIcon sx={{ color: '#667eea', mr: 1 }} />,
                    }}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        borderRadius: 2,
                        '&:hover fieldset': {
                          borderColor: '#667eea',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: '#667eea',
                        }
                      }
                    }}
                  />
                  
                  <TextField
                    fullWidth
                    label="Phone Number"
                    value={volunteerData.phoneNumber}
                    onChange={(e) => handleVolunteerDataChange('phoneNumber', e.target.value)}
                    required
                    InputProps={{
                      startAdornment: <PhoneIcon sx={{ color: '#667eea', mr: 1 }} />,
                    }}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        borderRadius: 2,
                        '&:hover fieldset': {
                          borderColor: '#667eea',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: '#667eea',
                        }
                      }
                    }}
                  />
                  
                  <FormControl fullWidth sx={{
                    '& .MuiOutlinedInput-root': {
                      borderRadius: 2,
                      '&:hover fieldset': {
                        borderColor: '#667eea',
                      },
                      '&.Mui-focused fieldset': {
                        borderColor: '#667eea',
                      }
                    }
                  }}>
                    <InputLabel>Preferred Contact Method</InputLabel>
                    <Select
                      value={volunteerData.preferedMethodOfcontact || ''}
                      label="Preferred Contact Method"
                      onChange={(e) => handleVolunteerDataChange('preferedMethodOfcontact', e.target.value)}
                      startAdornment={<ContactPhoneIcon sx={{ color: '#667eea', mr: 1, ml: 1 }} />}
                    >
                      {contactMethodOptions.map((option) => (
                        <MenuItem key={option.value} value={option.value}>
                          {option.label}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                  
                  <TextField
                    fullWidth
                    label="Good At"
                    multiline
                    rows={3}
                    value={volunteerData.goodAt}
                    onChange={(e) => handleVolunteerDataChange('goodAt', e.target.value)}
                    placeholder="Skills, expertise, areas of strength..."
                    InputProps={{
                      startAdornment: <StarIcon sx={{ color: '#667eea', mr: 1, alignSelf: 'flex-start', mt: 1 }} />,
                    }}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        borderRadius: 2,
                        '&:hover fieldset': {
                          borderColor: '#667eea',
                        },
                        '&.Mui-focused fieldset': {
                          borderColor: '#667eea',
                        }
                      }
                    }}
                  />
                  
                  <Box>
                    <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                      <InterestsIcon sx={{ color: '#667eea' }} />
                      <Typography variant="subtitle1" fontWeight="600">
                        Interests
                      </Typography>
                    </Stack>
                    <Autocomplete
                      multiple
                      options={commonInterests}
                      value={interests}
                      onChange={handleInterestsChange}
                      freeSolo
                      renderTags={(value: string[], getTagProps) =>
                        value.map((option: string, index: number) => (
                          <Chip
                            variant="outlined"
                            label={option}
                            {...getTagProps({ index })}
                            key={index}
                            sx={{
                              borderColor: '#667eea',
                              color: '#667eea',
                              '&:hover': {
                                backgroundColor: 'rgba(102, 126, 234, 0.08)'
                              }
                            }}
                          />
                        ))
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="Select or add interests"
                          placeholder="Add interests..."
                          helperText="Choose from suggestions or type custom interests"
                          sx={{
                            '& .MuiOutlinedInput-root': {
                              borderRadius: 2,
                              '&:hover fieldset': {
                                borderColor: '#667eea',
                              },
                              '&.Mui-focused fieldset': {
                                borderColor: '#667eea',
                              }
                            }
                          }}
                        />
                      )}
                    />
                  </Box>
                  
                  <Box sx={{
                    p: 3,
                    borderRadius: 2,
                    background: 'linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05))',
                    border: '1px solid rgba(102, 126, 234, 0.2)'
                  }}>
                    <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 2 }}>
                      <NotificationsIcon sx={{ color: '#667eea' }} />
                      <Typography variant="subtitle1" fontWeight="600">
                        Subscription Preferences
                      </Typography>
                    </Stack>
                    <Stack spacing={2}>
                      <FormControlLabel
                        control={
                          <Switch
                            checked={volunteerData.isEmailSubscribed || false}
                            onChange={(e) => handleVolunteerDataChange('isEmailSubscribed', e.target.checked)}
                            sx={{
                              '& .MuiSwitch-switchBase.Mui-checked': {
                                color: '#667eea',
                              },
                              '& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': {
                                backgroundColor: '#667eea',
                              },
                            }}
                          />
                        }
                        label="📧 Email Notifications"
                        sx={{ '& .MuiFormControlLabel-label': { fontWeight: 500 } }}
                      />
                      <FormControlLabel
                        control={
                          <Switch
                            checked={volunteerData.isPhoneSubscribed || false}
                            onChange={(e) => handleVolunteerDataChange('isPhoneSubscribed', e.target.checked)}
                            sx={{
                              '& .MuiSwitch-switchBase.Mui-checked': {
                                color: '#667eea',
                              },
                              '& .MuiSwitch-switchBase.Mui-checked + .MuiSwitch-track': {
                                backgroundColor: '#667eea',
                              },
                            }}
                          />
                        }
                        label="📱 SMS Notifications"
                        sx={{ '& .MuiFormControlLabel-label': { fontWeight: 500 } }}
                      />
                    </Stack>
                  </Box>
                </Stack>
              )}
            </TabPanel>
          </>
        )}
      </DialogContent>

      <DialogActions sx={{ 
        p: 3, 
        background: 'rgba(255, 255, 255, 0.95)',
        backdropFilter: 'blur(10px)',
        borderTop: '1px solid rgba(255, 255, 255, 0.2)',
        gap: 2
      }}>
        <Button 
          onClick={handleClose} 
          disabled={saving}
          variant="outlined"
          sx={{
            borderRadius: 3,
            px: 3,
            py: 1.5,
            borderColor: 'rgba(102, 126, 234, 0.3)',
            color: '#667eea',
            '&:hover': {
              borderColor: '#667eea',
              backgroundColor: 'rgba(102, 126, 234, 0.08)'
            }
          }}
        >
          Cancel
        </Button>
        <Button
          onClick={tabValue === 0 ? handleSaveUser : handleSaveVolunteer}
          variant="contained"
          disabled={saving || loading || (!userData && tabValue === 0) || (!volunteerData && tabValue === 1)}
          startIcon={saving ? <AppLoader size="xs" inline color="white" /> : <SaveIcon />}
          sx={{
            borderRadius: 3,
            px: 4,
            py: 1.5,
            background: 'linear-gradient(135deg, #667eea, #764ba2)',
            boxShadow: '0 4px 15px rgba(102, 126, 234, 0.3)',
            '&:hover': {
              background: 'linear-gradient(135deg, #5a67d8, #6b46c1)',
              boxShadow: '0 6px 20px rgba(102, 126, 234, 0.4)',
              transform: 'translateY(-1px)'
            },
            '&:disabled': {
              background: 'rgba(102, 126, 234, 0.3)',
              boxShadow: 'none'
            },
            transition: 'all 0.2s ease-in-out'
          }}
        >
          {saving ? 'Saving...' : `Save ${tabValue === 0 ? 'User' : 'Volunteer'} Info`}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default EditUserModal;
