// // IndividualRegister.tsx
// // ** React Imports
// import { useState } from 'react'

// // ** Next Import
// import { useRouter } from 'next/router'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import TextField from '@mui/material/TextField'
// import Box from '@mui/material/Box'
// import Grid from '@mui/material/Grid'
// import InputAdornment from '@mui/material/InputAdornment'
// import IconButton from '@mui/material/IconButton'
// import Alert from '@mui/material/Alert'
// import CircularProgress from '@mui/material/CircularProgress'
// import Typography from '@mui/material/Typography'
// import Autocomplete from '@mui/material/Autocomplete'

// // ** Third Party Imports
// import { useForm, Controller } from 'react-hook-form'
// import * as yup from 'yup'
// import { yupResolver } from '@hookform/resolvers/yup'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Data
// import { countries } from 'src/@fake-db/autocomplete'

// interface IndividualFormData {
//   firstName: string
//   lastName: string
//   email: string
//   phoneCode: string
//   phoneNumber: string
//   dateOfBirth: string
//   password: string
//   confirmPassword: string
//   address: string
//   city: string
//   state: string
//   zipCode: string
//   country: string
// }

// const schema = yup.object().shape({
//   firstName: yup.string().required('First name is required'),
//   lastName: yup.string().required('Last name is required'),
//   email: yup.string().email('Invalid email').required('Email is required'),
//   phoneCode: yup.string().required('Country code is required'),
//   phoneNumber: yup.string().required('Phone number is required'),
//   dateOfBirth: yup.string().required('Date of birth is required'),
//   password: yup.string().min(8, 'Password must be at least 8 characters').required('Password is required'),
//   confirmPassword: yup.string().oneOf([yup.ref('password')], 'Passwords must match').required('Confirm password is required'),
//   address: yup.string().required('Address is required'),
//   city: yup.string().required('City is required'),
//   state: yup.string().required('State is required'),
//   zipCode: yup.string().required('ZIP code is required'),
//   country: yup.string().required('Country is required')
// })

// const IndividualRegister = () => {
//   const router = useRouter()
//   const [showPassword, setShowPassword] = useState(false)
//   const [showConfirmPassword, setShowConfirmPassword] = useState(false)
//   const [isSubmitting, setIsSubmitting] = useState(false)
//   const [submitError, setSubmitError] = useState<string | null>(null)

//   const {
//     control,
//     handleSubmit,
//     formState: { errors }
//   } = useForm<IndividualFormData>({
//     mode: 'onBlur',
//     resolver: yupResolver(schema),
//     defaultValues: {
//       phoneCode: '+1'
//     }
//   })

//   const onSubmit = async (data: IndividualFormData) => {
//     setIsSubmitting(true)
//     setSubmitError(null)
    
//     const completeData = { 
//       ...data, 
//       phone: `${data.phoneCode} ${data.phoneNumber}`,
//       type: 'individual', 
//       registeredAt: new Date().toISOString() 
//     }
    
//     try {
//       await new Promise(resolve => setTimeout(resolve, 1500))
//       localStorage.setItem('registerData', JSON.stringify(completeData))
//       router.push('/verify-account')
//     } catch (error) {
//       setSubmitError('Registration failed. Please try again.')
//     } finally {
//       setIsSubmitting(false)
//     }
//   }

//   return (
//     <form onSubmit={handleSubmit(onSubmit)}>
//       {/* Personal Information Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
//         Personal Information
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='firstName'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='First Name'
//                 placeholder='John'
//                 error={!!errors.firstName}
//                 helperText={errors.firstName?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='lastName'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Last Name'
//                 placeholder='Doe'
//                 error={!!errors.lastName}
//                 helperText={errors.lastName?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='email'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 type='email'
//                 label='Email Address'
//                 placeholder='john@example.com'
//                 error={!!errors.email}
//                 helperText={errors.email?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='phoneCode'
//             control={control}
//             render={({ field: phoneCodeField }) => (
//               <Controller
//                 name='phoneNumber'
//                 control={control}
//                 render={({ field: phoneNumberField }) => (
//                   <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
//                     <Autocomplete
//                       sx={{ width: '180px' }}
//                       options={countries}
//                       autoHighlight
//                       getOptionLabel={(option) => `${option.code} +${option.phone}`}
//                       value={countries.find(c => c.phone === phoneCodeField.value) || null}
//                       onChange={(_, newValue) => {
//                         phoneCodeField.onChange(newValue?.phone || '+1')
//                       }}
//                       renderOption={(props, option) => (
//                         <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
//                           <img
//                             loading="lazy"
//                             width="20"
//                             src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
//                             srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
//                             alt=""
//                             style={{ marginRight: '8px' }}
//                           />
//                           {option.label} ({option.code}) +{option.phone}
//                         </Box>
//                       )}
//                       renderInput={(params) => (
//                         <TextField
//                           {...params}
//                           label="Country Code"
//                           error={!!errors.phoneCode}
//                           helperText={errors.phoneCode?.message}
//                           disabled={isSubmitting}
//                           inputProps={{
//                             ...params.inputProps,
//                             autoComplete: 'new-password',
//                           }}
//                         />
//                       )}
//                     />
//                     <TextField
//                       {...phoneNumberField}
//                       fullWidth
//                       label='Phone Number'
//                       placeholder='555 000 0000'
//                       error={!!errors.phoneNumber}
//                       helperText={errors.phoneNumber?.message}
//                       disabled={isSubmitting}
//                     />
//                   </Box>
//                 )}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='dateOfBirth'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Date of Birth'
//                 placeholder='DD/MM/YYYY'
//                 error={!!errors.dateOfBirth}
//                 helperText={errors.dateOfBirth?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Address Information Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Address Information
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='address'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Street Address'
//                 placeholder='123 Main Street'
//                 error={!!errors.address}
//                 helperText={errors.address?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='city'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='City'
//                 placeholder='New York'
//                 error={!!errors.city}
//                 helperText={errors.city?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='state'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='State'
//                 placeholder='NY'
//                 error={!!errors.state}
//                 helperText={errors.state?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='zipCode'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='ZIP Code'
//                 placeholder='10001'
//                 error={!!errors.zipCode}
//                 helperText={errors.zipCode?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='country'
//             control={control}
//             render={({ field }) => (
//               <Autocomplete
//                 options={countries}
//                 autoHighlight
//                 getOptionLabel={(option) => option.label}
//                 value={countries.find(c => c.label === field.value) || null}
//                 onChange={(_, newValue) => {
//                   field.onChange(newValue?.label || '')
//                 }}
//                 renderOption={(props, option) => (
//                   <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
//                     <img
//                       loading="lazy"
//                       width="20"
//                       src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
//                       srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
//                       alt=""
//                       style={{ marginRight: '8px' }}
//                     />
//                     {option.label} ({option.code})
//                   </Box>
//                 )}
//                 renderInput={(params) => (
//                   <TextField
//                     {...params}
//                     label='Country'
//                     placeholder='Select your country'
//                     error={!!errors.country}
//                     helperText={errors.country?.message}
//                     disabled={isSubmitting}
//                   />
//                 )}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Security Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Security
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='password'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Password'
//                 type={showPassword ? 'text' : 'password'}
//                 error={!!errors.password}
//                 helperText={errors.password?.message}
//                 disabled={isSubmitting}
//                 InputProps={{
//                   endAdornment: (
//                     <InputAdornment position='end'>
//                       <IconButton onClick={() => setShowPassword(!showPassword)} edge='end'>
//                         <Icon icon={showPassword ? 'tabler:eye-off' : 'tabler:eye'} fontSize={20} />
//                       </IconButton>
//                     </InputAdornment>
//                   )
//                 }}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='confirmPassword'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Confirm Password'
//                 type={showConfirmPassword ? 'text' : 'password'}
//                 error={!!errors.confirmPassword}
//                 helperText={errors.confirmPassword?.message}
//                 disabled={isSubmitting}
//                 InputProps={{
//                   endAdornment: (
//                     <InputAdornment position='end'>
//                       <IconButton onClick={() => setShowConfirmPassword(!showConfirmPassword)} edge='end'>
//                         <Icon icon={showConfirmPassword ? 'tabler:eye-off' : 'tabler:eye'} fontSize={20} />
//                       </IconButton>
//                     </InputAdornment>
//                   )
//                 }}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {submitError && (
//         <Alert severity="error" sx={{ mt: 3 }} onClose={() => setSubmitError(null)}>
//           {submitError}
//         </Alert>
//       )}

//       <Button
//         type='submit'
//         fullWidth
//         variant='contained'
//         size='large'
//         disabled={isSubmitting}
//         sx={{ mt: 4, py: 1.2, borderRadius: 2, textTransform: 'none', fontWeight: 600 }}
//       >
//         {isSubmitting ? <CircularProgress size={24} color="inherit" /> : 'Create Account'}
//       </Button>
//     </form>
//   )
// }

// export default IndividualRegister

// IndividualRegister.tsx
// ** React Imports

// import { useState } from 'react'

// // ** Next Import
// import { useRouter } from 'next/router'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import TextField from '@mui/material/TextField'
// import Box from '@mui/material/Box'
// import Grid from '@mui/material/Grid'
// import InputAdornment from '@mui/material/InputAdornment'
// import IconButton from '@mui/material/IconButton'
// import CircularProgress from '@mui/material/CircularProgress'
// import Typography from '@mui/material/Typography'
// import Autocomplete from '@mui/material/Autocomplete'

// // ** Third Party Imports
// import { useForm, Controller } from 'react-hook-form'
// import * as yup from 'yup'
// import { yupResolver } from '@hookform/resolvers/yup'

// // ** Icon Imports
// import Icon from 'src/@core/components/icon'

// // ** Toast Imports
// import toast from 'react-hot-toast'

// // ** CryptoJS
// import CryptoJS from 'crypto-js'

// // ** Axios & Endpoints
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

// // ** Data
// import { countries } from 'src/@fake-db/autocomplete'

// interface IndividualFormData {
//   firstName: string
//   lastName: string
//   email: string
//   phoneCode: string
//   dialCountryCode: string
//   phoneNumber: string
//   dateOfBirth: string
//   password: string
//   confirmPassword: string
//   address: string
//   city: string
//   state: string
//   zipCode: string
//   country: string
//   ssn: string
// }

// // Updated password validation to match API requirements
// const schema = yup.object().shape({
//   firstName: yup.string().required('First name is required'),
//   lastName: yup.string().required('Last name is required'),
//   email: yup.string().email('Invalid email').required('Email is required'),
//   phoneCode: yup.string().required('Country code is required'),
//   dialCountryCode: yup.string().required('Dial country code is required'),
//   phoneNumber: yup.string().required('Phone number is required'),
//   dateOfBirth: yup.string()
//     .required('Date of birth is required')
//     .matches(/^\d{2}\/\d{2}\/\d{4}$/, 'Date must be in DD/MM/YYYY format'),
//   password: yup.string()
//     .min(12, 'Password must be at least 12 characters')
//     .matches(
//       /^[A-Za-z0-9!@#$%^&*]+$/,
//       'Password may contain letters, numbers, and special characters (! @ # $ % ^ & *)'
//     )
//     .required('Password is required'),
//   confirmPassword: yup.string().oneOf([yup.ref('password')], 'Passwords must match').required('Confirm password is required'),
//   address: yup.string().required('Address is required'),
//   city: yup.string().required('City is required'),
//   state: yup.string().required('State is required'),
//   zipCode: yup.string().required('ZIP code is required'),
//   country: yup.string().required('Country is required'),
//   ssn: yup.string().matches(/^\d{3}-\d{2}-\d{4}$/, 'SSN must be in format XXX-XX-XXXX').required('SSN is required')
// })

// const IndividualRegister = () => {
//   const router = useRouter()
//   const [showPassword, setShowPassword] = useState(false)
//   const [showConfirmPassword, setShowConfirmPassword] = useState(false)
//   const [isSubmitting, setIsSubmitting] = useState(false)

//   // AES Encryption function
//   const encryptAES = (text: string): string => {
//     const secretKey = 'zMWH89JA7Nix4HM+ij3sF6KO3ZumDInh/SQKutvhuO8='

//     const key = CryptoJS.SHA256(secretKey)
//     const iv = CryptoJS.lib.WordArray.random(16)

//     const encrypted = CryptoJS.AES.encrypt(text, key, {
//       iv: iv,
//       mode: CryptoJS.mode.CBC,
//       padding: CryptoJS.pad.Pkcs7
//     })

//     const combined = iv.clone().concat(encrypted.ciphertext)

//     return CryptoJS.enc.Base64.stringify(combined)
//   }

//   // Format date from DD/MM/YYYY to YYYY-MM-DD
//   const formatDateForAPI = (dateString: string): string => {
//     if (!dateString) return ''
    
//     if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) {
//       return dateString
//     }
    
//     const parts = dateString.split('/')
//     if (parts.length === 3) {
//       const day = parts[0].padStart(2, '0')
//       const month = parts[1].padStart(2, '0')
//       const year = parts[2]
//       return `${year}-${month}-${day}`
//     }
    
//     return dateString
//   }

//   // Map backend validation errors to user-friendly messages
//   const mapBackendErrorToMessage = (content: string): string => {
//     if (content.includes('Password must be at least 12 characters long')) {
//       return '❌ Password must be at least 12 characters long'
//     }
//     if (content.includes('Password may contain letters, numbers, and special characters')) {
//       return '❌ Password may contain letters, numbers, and special characters (! @ # $ % ^ & *)'
//     }
//     if (content.includes('Email is already registered')) {
//       return '❌ This email is already registered. Please use a different email or login.'
//     }
//     if (content.includes('Invalid email format')) {
//       return '❌ Please enter a valid email address'
//     }
//     if (content.includes('SSN already exists')) {
//       return '❌ This SSN is already registered'
//     }
//     if (content.includes('Phone number already exists')) {
//       return '❌ This phone number is already registered'
//     }
//     if (content.includes('Date of birth')) {
//       return '❌ Please enter a valid date of birth in DD/MM/YYYY format'
//     }
//     return content
//   }

//   const {
//     control,
//     handleSubmit,
//     formState: { errors },
//     setValue,
//     watch
//   } = useForm<IndividualFormData>({
//     mode: 'onBlur',
//     resolver: yupResolver(schema),
//     defaultValues: {
//       phoneCode: 'US',
//       dialCountryCode: '+1',
//       ssn: ''
//     }
//   })

//   const selectedPhoneCode = watch('phoneCode')

//   const onSubmit = async (data: IndividualFormData) => {
//     setIsSubmitting(true)
    
//     try {
//       // Encrypt password and confirmPassword
//       const encryptedPassword = encryptAES(data.password)
//       const encryptedConfirmPassword = encryptAES(data.confirmPassword)
      
//       // Format date of birth
//       const formattedDateOfBirth = formatDateForAPI(data.dateOfBirth)
      
//       // Prepare API request body
//       const requestBody = {
//         firstName: data.firstName,
//         lastName: data.lastName,
//         emailId: data.email,
//         mobileNumber: data.phoneNumber,
//         countryCode: data.dialCountryCode,
//         dialCountryCode: data.phoneCode,
//         address: data.address,
//         city: data.city,
//         state: data.state,
//         country: data.country,
//         password: encryptedPassword,
//         confirmPassword: encryptedConfirmPassword,
//         userAccountType: "Individual",
//         ssn: data.ssn,
//         dateOfBirth: formattedDateOfBirth,
//         postalCode: data.zipCode
//       }
      
//       // Call the API
//       const response = await axios.post(endpoints.auth.register, requestBody)
      
//       // Success handling
//       if (response.data && (response.data.code === 200 || response.status === 200 || response.status === 201)) {
//         toast.success('Account created successfully! Please verify your email.')
        
//         if (response.data.token) {
//           localStorage.setItem('accessToken', response.data.token)
//         }
        
//         localStorage.setItem('registerEmail', data.email)
        
//         // Redirect to verify account page
//         setTimeout(() => {
//           router.push('/login')
//         }, 1500)
//       } else {
//         // Handle unexpected success response
//         toast.error(response.data?.message || 'Registration failed. Please try again.')
//       }
      
//     } catch (error: any) {
//       console.error('Registration error:', error)
      
//       // Handle backend validation errors
//       if (error?.response?.data?.content) {
//         // Specific field validation from backend
//         const errorMessage = mapBackendErrorToMessage(error.response.data.content)
//         toast.error(errorMessage)
//       } else if (error?.response?.data?.message) {
//         // General message from backend
//         toast.error(error.response.data.message)
//       } else if (error?.response?.data?.detail) {
//         // Error detail from backend
//         toast.error(error.response.data.detail)
//       } else if (error?.response?.data?.errors) {
//         // Multiple validation errors
//         const errors = error.response.data.errors
//         if (Array.isArray(errors)) {
//           errors.forEach((err: string) => toast.error(err))
//         } else if (typeof errors === 'object') {
//           Object.values(errors).forEach((err: any) => {
//             toast.error(Array.isArray(err) ? err[0] : err)
//           })
//         }
//       } else if (error?.message) {
//         toast.error(error.message)
//       } else {
//         toast.error('Registration failed. Please check your connection and try again.')
//       }
//     } finally {
//       setIsSubmitting(false)
//     }
//   }

//   const getSelectedCountry = () => {
//     return countries.find(c => c.code === selectedPhoneCode) || null
//   }

//   return (
//     <form onSubmit={handleSubmit(onSubmit)}>
//       {/* Personal Information Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
//         Personal Information
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='firstName'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='First Name'
//                 placeholder='John'
//                 error={!!errors.firstName}
//                 helperText={errors.firstName?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='lastName'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Last Name'
//                 placeholder='Doe'
//                 error={!!errors.lastName}
//                 helperText={errors.lastName?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='email'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 type='email'
//                 label='Email Address'
//                 placeholder='john@example.com'
//                 error={!!errors.email}
//                 helperText={errors.email?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='phoneCode'
//             control={control}
//             render={({ field: phoneCodeField }) => (
//               <Controller
//                 name='phoneNumber'
//                 control={control}
//                 render={({ field: phoneNumberField }) => (
//                   <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
//                     <Autocomplete
//                       sx={{ width: '200px' }}
//                       options={countries}
//                       autoHighlight
//                       getOptionLabel={(option) => `${option.code} +${option.phone}`}
//                       value={getSelectedCountry()}
//                       onChange={(_, newValue) => {
//                         if (newValue) {
//                           phoneCodeField.onChange(newValue.code)
//                           setValue('dialCountryCode', `+${newValue.phone}`)
//                         }
//                       }}
//                       renderOption={(props, option) => (
//                         <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
//                           <img
//                             loading="lazy"
//                             width="20"
//                             src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
//                             srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
//                             alt=""
//                             style={{ marginRight: '8px' }}
//                           />
//                           {option.label} ({option.code}) +{option.phone}
//                         </Box>
//                       )}
//                       renderInput={(params) => (
//                         <TextField
//                           {...params}
//                           label="Country Code"
//                           error={!!errors.phoneCode}
//                           helperText={errors.phoneCode?.message}
//                           disabled={isSubmitting}
//                           inputProps={{
//                             ...params.inputProps,
//                             autoComplete: 'new-password',
//                           }}
//                         />
//                       )}
//                     />
//                     <TextField
//                       {...phoneNumberField}
//                       fullWidth
//                       label='Phone Number'
//                       placeholder='555 000 0000'
//                       error={!!errors.phoneNumber}
//                       helperText={errors.phoneNumber?.message}
//                       disabled={isSubmitting}
//                     />
//                   </Box>
//                 )}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='dateOfBirth'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Date of Birth'
//                 placeholder='DD/MM/YYYY'
//                 helperText={errors.dateOfBirth?.message || 'Format: DD/MM/YYYY (e.g., 15/05/1985)'}
//                 error={!!errors.dateOfBirth}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='ssn'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='SSN (Social Security Number)'
//                 placeholder='XXX-XX-XXXX'
//                 helperText={errors.ssn?.message || 'Format: XXX-XX-XXXX'}
//                 error={!!errors.ssn}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Address Information Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Address Information
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='address'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Street Address'
//                 placeholder='123 Main Street'
//                 error={!!errors.address}
//                 helperText={errors.address?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='city'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='City'
//                 placeholder='New York'
//                 error={!!errors.city}
//                 helperText={errors.city?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='state'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='State'
//                 placeholder='NY'
//                 error={!!errors.state}
//                 helperText={errors.state?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='zipCode'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='ZIP Code'
//                 placeholder='10001'
//                 error={!!errors.zipCode}
//                 helperText={errors.zipCode?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='country'
//             control={control}
//             render={({ field }) => (
//               <Autocomplete
//                 options={countries}
//                 autoHighlight
//                 getOptionLabel={(option) => option.label}
//                 value={countries.find(c => c.label === field.value) || null}
//                 onChange={(_, newValue) => {
//                   field.onChange(newValue?.label || '')
//                 }}
//                 renderOption={(props, option) => (
//                   <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
//                     <img
//                       loading="lazy"
//                       width="20"
//                       src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
//                       srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
//                       alt=""
//                       style={{ marginRight: '8px' }}
//                     />
//                     {option.label} ({option.code})
//                   </Box>
//                 )}
//                 renderInput={(params) => (
//                   <TextField
//                     {...params}
//                     label='Country'
//                     placeholder='Select your country'
//                     error={!!errors.country}
//                     helperText={errors.country?.message}
//                     disabled={isSubmitting}
//                   />
//                 )}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Security Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Security
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='password'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Password'
//                 type={showPassword ? 'text' : 'password'}
//                 error={!!errors.password}
//                 helperText={errors.password?.message || 'Password must be at least 12 characters'}
//                 disabled={isSubmitting}
//                 InputProps={{
//                   endAdornment: (
//                     <InputAdornment position='end'>
//                       <IconButton onClick={() => setShowPassword(!showPassword)} edge='end'>
//                         <Icon icon={showPassword ? 'tabler:eye-off' : 'tabler:eye'} fontSize={20} />
//                       </IconButton>
//                     </InputAdornment>
//                   )
//                 }}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='confirmPassword'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Confirm Password'
//                 type={showConfirmPassword ? 'text' : 'password'}
//                 error={!!errors.confirmPassword}
//                 helperText={errors.confirmPassword?.message}
//                 disabled={isSubmitting}
//                 InputProps={{
//                   endAdornment: (
//                     <InputAdornment position='end'>
//                       <IconButton onClick={() => setShowConfirmPassword(!showConfirmPassword)} edge='end'>
//                         <Icon icon={showConfirmPassword ? 'tabler:eye-off' : 'tabler:eye'} fontSize={20} />
//                       </IconButton>
//                     </InputAdornment>
//                   )
//                 }}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       <Button
//         type='submit'
//         fullWidth
//         variant='contained'
//         size='large'
//         disabled={isSubmitting}
//         sx={{ mt: 4, py: 1.2, borderRadius: 2, textTransform: 'none', fontWeight: 600 }}
//       >
//         {isSubmitting ? <CircularProgress size={24} color="inherit" /> : 'Create Account'}
//       </Button>
//     </form>
//   )
// }

// export default IndividualRegister


// final 
import { useState, useRef } from 'react'

// ** Next Import
import { useRouter } from 'next/router'

// ** MUI Components
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
import Box from '@mui/material/Box'
import Grid from '@mui/material/Grid'
import InputAdornment from '@mui/material/InputAdornment'
import IconButton from '@mui/material/IconButton'
import CircularProgress from '@mui/material/CircularProgress'
import Typography from '@mui/material/Typography'
import Autocomplete from '@mui/material/Autocomplete'

// ** Third Party Imports
import { useForm, Controller } from 'react-hook-form'
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'

// ** Icon Imports
import Icon from 'src/@core/components/icon'

// ** Toast Imports
import toast from 'react-hot-toast'

// ** CryptoJS
import CryptoJS from 'crypto-js'

// ** Axios & Endpoints
import axios from 'src/configs/axios'
import endpoints from 'src/configs/endpoints'

// ** Data
import { countries } from 'src/@fake-db/autocomplete'

interface IndividualFormData {
  firstName: string
  lastName: string
  email: string
  phoneCode: string
  dialCountryCode: string
  phoneNumber: string
  dateOfBirth: string
  password: string
  confirmPassword: string
  address: string
  city: string
  state: string
  zipCode: string
  country: string
  ssn: string
}

// Updated password validation to match API requirements
const schema = yup.object().shape({
  firstName: yup.string().required('First name is required'),
  lastName: yup.string().required('Last name is required'),
  email: yup.string().email('Invalid email').required('Email is required'),
  phoneCode: yup.string().required('Country code is required'),
  dialCountryCode: yup.string().required('Dial country code is required'),
  phoneNumber: yup.string().required('Phone number is required'),
  dateOfBirth: yup.string()
    .required('Date of birth is required')
    .matches(/^\d{2}\/\d{2}\/\d{4}$/, 'Date must be in DD/MM/YYYY format'),
  password: yup.string()
    .min(12, 'Password must be at least 12 characters')
    .matches(
      /^[A-Za-z0-9!@#$%^&*]+$/,
      'Password may contain letters, numbers, and special characters (! @ # $ % ^ & *)'
    )
    .required('Password is required'),
  confirmPassword: yup.string().oneOf([yup.ref('password')], 'Passwords must match').required('Confirm password is required'),
  address: yup.string().required('Address is required'),
  city: yup.string().required('City is required'),
  state: yup.string().required('State is required'),
  zipCode: yup.string().required('ZIP code is required'),
  country: yup.string().required('Country is required'),
  ssn: yup.string().matches(/^\d{3}-\d{3}-\d{3}$/, 'SSN must be in format XXX-XXX-XXX').required('SSN is required')
})

const IndividualRegister = () => {
  const router = useRouter()
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)
  
  // Refs for input fields
  const dateOfBirthInputRef = useRef<HTMLInputElement>(null)
  const ssnInputRef = useRef<HTMLInputElement>(null)

  // AES Encryption function - using environment variable
  const encryptAES = (text: string): string => {
    const secretKey = process.env.NEXT_PUBLIC_CRYPTO_SECRET_KEY || ''
    

    const key = CryptoJS.SHA256(secretKey)
    const iv = CryptoJS.lib.WordArray.random(16)

    const encrypted = CryptoJS.AES.encrypt(text, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })

    const combined = iv.clone().concat(encrypted.ciphertext)

    return CryptoJS.enc.Base64.stringify(combined)
  }

  // Format date from DD/MM/YYYY to YYYY-MM-DD
  const formatDateForAPI = (dateString: string): string => {
    if (!dateString) return ''
    
    if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) {
      return dateString
    }
    
    const parts = dateString.split('/')
    if (parts.length === 3) {
      const day = parts[0].padStart(2, '0')
      const month = parts[1].padStart(2, '0')
      const year = parts[2]
      return `${year}-${month}-${day}`
    }
    
    return dateString
  }

  // Extract field name from error message and return clean error message
  const extractErrorMessage = (errorMessage: string): string => {
    if (!errorMessage || typeof errorMessage !== 'string') {
      return 'An error occurred. Please try again.'
    }

    // Check if the error message contains a colon (field: message format)
    if (errorMessage.includes(':')) {
      const parts = errorMessage.split(':')

      // Return everything after the first colon, trimmed
      return parts.slice(1).join(':').trim()
    }

    // Check for common patterns with field names
    const fieldPatterns = [
      /^firstName\s*/i,
      /^lastName\s*/i,
      /^email\s*/i,
      /^phoneCode\s*/i,
      /^phoneNumber\s*/i,
      /^dateOfBirth\s*/i,
      /^password\s*/i,
      /^confirmPassword\s*/i,
      /^address\s*/i,
      /^city\s*/i,
      /^state\s*/i,
      /^zipCode\s*/i,
      /^country\s*/i,
      /^ssn\s*/i,
      /^dialCountryCode\s*/i
    ]

    for (const pattern of fieldPatterns) {
      if (pattern.test(errorMessage)) {
        return errorMessage.replace(pattern, '').trim()
      }
    }

    // If no pattern matches, return the original message
    return errorMessage
  }

  // Map backend validation errors to user-friendly messages
  const mapBackendErrorToMessage = (content: any): string => {
    // If content is not a string, convert it to a string or return a default message
    if (typeof content !== 'string') {
      // If it's an object, try to stringify it
      if (typeof content === 'object') {
        try {
          // If it's an object with field errors, extract and format them
          if (content !== null && !Array.isArray(content)) {
            const messages: string[] = []
            for (const [key, value] of Object.entries(content)) {
              if (typeof value === 'string') {
                messages.push(extractErrorMessage(value))
              } else if (Array.isArray(value)) {
                value.forEach((v: any) => {
                  if (typeof v === 'string') {
                    messages.push(extractErrorMessage(v))
                  }
                })
              }
            }
            if (messages.length > 0) {
              return messages.join('. ')
            }
          }
          return JSON.stringify(content)
        } catch {
          return 'An error occurred. Please try again.'
        }
      }
      return String(content || 'An error occurred. Please try again.')
    }

    // Extract clean error message without field names
    const cleanMessage = extractErrorMessage(content)

    // Map specific error messages to user-friendly versions
    if (cleanMessage.toLowerCase().includes('password must be at least 12 characters long') || 
        cleanMessage.toLowerCase().includes('password must be at least 12 characters')) {
      return '❌ Password must be at least 12 characters long'
    }
    if (cleanMessage.toLowerCase().includes('password may contain letters, numbers, and special characters')) {
      return '❌ Password may contain letters, numbers, and special characters (! @ # $ % ^ & *)'
    }
    if (cleanMessage.toLowerCase().includes('email is already registered') || 
        cleanMessage.toLowerCase().includes('email already exists')) {
      return '❌ This email is already registered. Please use a different email or login.'
    }
    if (cleanMessage.toLowerCase().includes('invalid email format') || 
        cleanMessage.toLowerCase().includes('invalid email')) {
      return '❌ Please enter a valid email address'
    }
    if (cleanMessage.toLowerCase().includes('ssn already exists')) {
      return '❌ This SSN is already registered'
    }
    if (cleanMessage.toLowerCase().includes('phone number already exists')) {
      return '❌ This phone number is already registered'
    }
    if (cleanMessage.toLowerCase().includes('date of birth')) {
      return '❌ Please enter a valid date of birth in DD/MM/YYYY format'
    }
    if (cleanMessage.toLowerCase().includes('only contain alphabetic characters')) {
      return '❌ Only alphabetic characters and spaces are allowed'
    }
    if (cleanMessage.toLowerCase().includes('required') && 
        (cleanMessage.toLowerCase().includes('first name') || 
         cleanMessage.toLowerCase().includes('last name') ||
         cleanMessage.toLowerCase().includes('email') ||
         cleanMessage.toLowerCase().includes('phone') ||
         cleanMessage.toLowerCase().includes('password'))) {
      return '❌ This field is required'
    }
    
    // Return the cleaned message with a warning icon if it's not empty
    return cleanMessage ? `❌ ${cleanMessage}` : 'An error occurred. Please try again.'
  }

  // Format Date of Birth with masking
  const formatDateOfBirth = (value: string): string => {
    // Remove all non-numeric characters
    const cleaned = value.replace(/\D/g, '')
    
    // Limit to 8 digits (DDMMYYYY)
    const limited = cleaned.slice(0, 8)
    
    // Format with slashes
    let formatted = ''
    for (let i = 0; i < limited.length; i++) {
      if (i === 2 || i === 4) {
        formatted += '/'
      }
      formatted += limited[i]
    }
    
    return formatted
  }

  // Format SSN with masking - XXX-XXX-XXX format
  const formatSSN = (value: string): string => {
    // Remove all non-numeric characters
    const cleaned = value.replace(/\D/g, '')
    
    // Limit to 9 digits
    const limited = cleaned.slice(0, 9)
    
    // Format with dashes - XXX-XXX-XXX
    let formatted = ''
    for (let i = 0; i < limited.length; i++) {
      if (i === 3 || i === 6) {
        formatted += '-'
      }
      formatted += limited[i]
    }
    
    return formatted
  }

  // Handle Date of Birth input change
  const handleDateOfBirthChange = (e: React.ChangeEvent<HTMLInputElement>, onChange: (value: string) => void) => {
    const rawValue = e.target.value
    const formatted = formatDateOfBirth(rawValue)
    
    // Update the form state
    onChange(formatted)
    
    // Update the input value directly
    if (dateOfBirthInputRef.current) {
      dateOfBirthInputRef.current.value = formatted
    }
  }

  // Handle SSN input change
  const handleSSNChange = (e: React.ChangeEvent<HTMLInputElement>, onChange: (value: string) => void) => {
    const rawValue = e.target.value
    const formatted = formatSSN(rawValue)
    
    // Update the form state
    onChange(formatted)
    
    // Update the input value directly
    if (ssnInputRef.current) {
      ssnInputRef.current.value = formatted
    }
  }

  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    watch
  } = useForm<IndividualFormData>({
    mode: 'onBlur',
    resolver: yupResolver(schema),
    defaultValues: {
      phoneCode: 'US',
      dialCountryCode: '+1',
      ssn: ''
    }
  })

  const selectedPhoneCode = watch('phoneCode')

  const onSubmit = async (data: IndividualFormData) => {
    setIsSubmitting(true)
    
    try {
      // Encrypt password and confirmPassword
      const encryptedPassword = encryptAES(data.password)
      const encryptedConfirmPassword = encryptAES(data.confirmPassword)

      
      
      // Format date of birth
      const formattedDateOfBirth = formatDateForAPI(data.dateOfBirth)
      
      // Prepare API request body
      const requestBody = {
        firstName: data.firstName,
        lastName: data.lastName,
        emailId: data.email,
        mobileNumber: data.phoneNumber,
        countryCode: data.dialCountryCode,
        dialCountryCode: data.phoneCode,
        address: data.address,
        city: data.city,
        state: data.state,
        country: data.country,
        password: encryptedPassword,
        confirmPassword: encryptedConfirmPassword,
        userAccountType: "Individual",
        ssn: data.ssn,
        dateOfBirth: formattedDateOfBirth,
        postalCode: data.zipCode
      }
      
      // Call the API
      const response = await axios.post(endpoints.auth.register, requestBody)
      
      // Success handling
      if (response.data && (response.data.code === 200 || response.status === 200 || response.status === 201)) {
        toast.success('Account created successfully! Please verify your email.')
        
        if (response.data.token) {
          localStorage.setItem('accessToken', response.data.token)
        }
        
        localStorage.setItem('registerEmail', data.email)
        
        // Redirect to verify account page
        setTimeout(() => {
          router.push('/login')
        }, 1500)
      } else {
        // Handle unexpected success response
        toast.error(response.data?.message || 'Registration failed. Please try again.')
      }
      
    } catch (error: any) {
      console.error('Registration error:', error)
      
      // Handle backend validation errors
      if (error?.response?.data) {
        const errorData = error.response.data
        
        // Check if errorData is an object with field-specific errors
        if (typeof errorData === 'object' && errorData !== null) {
          // Check if it's a field error object (like {"firstName": "First name only contain alphabetic characters and space."})
          const hasFieldErrors = Object.keys(errorData).some(key => 
            typeof errorData[key] === 'string' && 
            (key === 'firstName' || key === 'lastName' || key === 'email' || 
             key === 'password' || key === 'ssn' || key === 'phoneNumber')
          )
          
          if (hasFieldErrors) {
            // Process each field error
            const errorMessages: string[] = []
            for (const [field, message] of Object.entries(errorData)) {
              if (typeof message === 'string') {
                const cleanMessage = mapBackendErrorToMessage(message)
                errorMessages.push(cleanMessage)
              }
            }

            // Show all error messages
            if (errorMessages.length > 0) {
              errorMessages.forEach(msg => toast.error(msg))
            }
          } 

          // Check for content field
          else if (errorData.content) {
            const errorMessage = mapBackendErrorToMessage(errorData.content)
            toast.error(errorMessage)
          } 

          // Check for message field
          else if (errorData.message) {
            const errorMessage = mapBackendErrorToMessage(errorData.message)
            toast.error(errorMessage)
          }

          // Check for detail field
          else if (errorData.detail) {
            const errorMessage = mapBackendErrorToMessage(errorData.detail)
            toast.error(errorMessage)
          }

          // Check for errors field (multiple validation errors)
          else if (errorData.errors) {
            const errors = errorData.errors
            if (Array.isArray(errors)) {
              errors.forEach((err: any) => {
                const errorMessage = mapBackendErrorToMessage(err)
                toast.error(errorMessage)
              })
            } else if (typeof errors === 'object') {
              Object.values(errors).forEach((err: any) => {
                const errorMessage = mapBackendErrorToMessage(Array.isArray(err) ? err[0] : err)
                toast.error(errorMessage)
              })
            }
          } else {
            // If no specific error field found, show a generic message
            toast.error('Registration failed. Please check your information and try again.')
          }
        } else {
          // If errorData is not an object, pass it to mapBackendErrorToMessage
          const errorMessage = mapBackendErrorToMessage(errorData)
          toast.error(errorMessage)
        }
      } else if (error?.message) {
        toast.error(error.message)
      } else {
        toast.error('Registration failed. Please check your connection and try again.')
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  const getSelectedCountry = () => {
    return countries.find(c => c.code === selectedPhoneCode) || null
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* Personal Information Section */}
      <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
        Personal Information
      </Typography>
      
      <Grid container spacing={3}>
        <Grid item xs={12} sm={6}>
          <Controller
            name='firstName'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='First Name'
                placeholder='John'
                error={!!errors.firstName}
                helperText={errors.firstName?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <Controller
            name='lastName'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='Last Name'
                placeholder='Doe'
                error={!!errors.lastName}
                helperText={errors.lastName?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>

        <Grid item xs={12}>
          <Controller
            name='email'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                type='email'
                label='Email Address'
                placeholder='john@example.com'
                error={!!errors.email}
                helperText={errors.email?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>

        <Grid item xs={12}>
          <Controller
            name='phoneCode'
            control={control}
            render={({ field: phoneCodeField }) => (
              <Controller
                name='phoneNumber'
                control={control}
                render={({ field: phoneNumberField }) => (
                  <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
                    <Autocomplete
                      sx={{ width: '200px' }}
                      options={countries}
                      autoHighlight
                      getOptionLabel={(option) => `${option.code} +${option.phone}`}
                      value={getSelectedCountry()}
                      onChange={(_, newValue) => {
                        if (newValue) {
                          phoneCodeField.onChange(newValue.code)
                          setValue('dialCountryCode', `+${newValue.phone}`)
                        }
                      }}
                      renderOption={(props, option) => (
                        <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
                          <img
                            loading="lazy"
                            width="20"
                            src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
                            srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
                            alt=""
                            style={{ marginRight: '8px' }}
                          />
                          {option.label} ({option.code}) +{option.phone}
                        </Box>
                      )}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="Country Code"
                          error={!!errors.phoneCode}
                          helperText={errors.phoneCode?.message}
                          disabled={isSubmitting}
                          inputProps={{
                            ...params.inputProps,
                            autoComplete: 'new-password',
                          }}
                        />
                      )}
                    />
                    <TextField
                      {...phoneNumberField}
                      fullWidth
                      label='Phone Number'
                      placeholder='555 000 0000'
                      error={!!errors.phoneNumber}
                      helperText={errors.phoneNumber?.message}
                      disabled={isSubmitting}
                    />
                  </Box>
                )}
              />
            )}
          />
        </Grid>

        <Grid item xs={12}>
          <Controller
            name='dateOfBirth'
            control={control}
            render={({ field }) => (
              <TextField
                inputRef={dateOfBirthInputRef}
                fullWidth
                label='Date of Birth'
                placeholder='DD/MM/YYYY'
                helperText={errors.dateOfBirth?.message || 'Format: DD/MM/YYYY (e.g., 15/05/1985)'}
                error={!!errors.dateOfBirth}
                disabled={isSubmitting}
                value={field.value}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleDateOfBirthChange(e, field.onChange)}
                onKeyDown={(e) => {
                  // Allow backspace, delete, tab, escape, enter, arrow keys
                  const allowedKeys = ['Backspace', 'Delete', 'Tab', 'Escape', 'Enter', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']
                  if (allowedKeys.includes(e.key)) {
                    return
                  }

                  // Prevent non-numeric input
                  if (!/^\d$/.test(e.key)) {
                    e.preventDefault()
                  }
                }}
                onPaste={(e) => {
                  e.preventDefault()
                  const pastedData = e.clipboardData.getData('text/plain')
                  const cleaned = pastedData.replace(/\D/g, '').slice(0, 8)
                  const formatted = formatDateOfBirth(cleaned)
                  field.onChange(formatted)
                  if (dateOfBirthInputRef.current) {
                    dateOfBirthInputRef.current.value = formatted
                  }
                }}
                inputProps={{
                  maxLength: 10,
                  autoComplete: 'off'
                }}
              />
            )}
          />
        </Grid>

        <Grid item xs={12}>
          <Controller
            name='ssn'
            control={control}
            render={({ field }) => (
              <TextField
                inputRef={ssnInputRef}
                fullWidth
                label='SSN/ ITIN/ TIN'
                placeholder='XXX-XXX-XXX'
                helperText={errors.ssn?.message || 'Format: XXX-XXX-XXX'}
                error={!!errors.ssn}
                disabled={isSubmitting}
                value={field.value}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleSSNChange(e, field.onChange)}
                onKeyDown={(e) => {
                  // Allow backspace, delete, tab, escape, enter, arrow keys
                  const allowedKeys = ['Backspace', 'Delete', 'Tab', 'Escape', 'Enter', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']
                  if (allowedKeys.includes(e.key)) {
                    return
                  }

                  // Prevent non-numeric input
                  if (!/^\d$/.test(e.key)) {
                    e.preventDefault()
                  }
                }}
                onPaste={(e) => {
                  e.preventDefault()
                  const pastedData = e.clipboardData.getData('text/plain')
                  const cleaned = pastedData.replace(/\D/g, '').slice(0, 9)
                  const formatted = formatSSN(cleaned)
                  field.onChange(formatted)
                  if (ssnInputRef.current) {
                    ssnInputRef.current.value = formatted
                  }
                }}
                inputProps={{
                  maxLength: 11,
                  autoComplete: 'off'
                }}
              />
            )}
          />
        </Grid>
      </Grid>

      {/* Address Information Section */}
      <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
        Address Information
      </Typography>
      
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Controller
            name='address'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='Street Address'
                placeholder='123 Main Street'
                error={!!errors.address}
                helperText={errors.address?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>

        <Grid item xs={12} sm={4}>
          <Controller
            name='city'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='City'
                placeholder='New York'
                error={!!errors.city}
                helperText={errors.city?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>

        <Grid item xs={12} sm={4}>
          <Controller
            name='state'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='State'
                placeholder='NY'
                error={!!errors.state}
                helperText={errors.state?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>

        <Grid item xs={12} sm={4}>
          <Controller
            name='zipCode'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='ZIP Code'
                placeholder='10001'
                error={!!errors.zipCode}
                helperText={errors.zipCode?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>

        <Grid item xs={12}>
          <Controller
            name='country'
            control={control}
            render={({ field }) => (
              <Autocomplete
                options={countries}
                autoHighlight
                getOptionLabel={(option) => option.label}
                value={countries.find(c => c.label === field.value) || null}
                onChange={(_, newValue) => {
                  field.onChange(newValue?.label || '')
                }}
                renderOption={(props, option) => (
                  <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
                    <img
                      loading="lazy"
                      width="20"
                      src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
                      srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
                      alt=""
                      style={{ marginRight: '8px' }}
                    />
                    {option.label} ({option.code})
                  </Box>
                )}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    label='Country'
                    placeholder='Select your country'
                    error={!!errors.country}
                    helperText={errors.country?.message}
                    disabled={isSubmitting}
                  />
                )}
              />
            )}
          />
        </Grid>
      </Grid>

      {/* Security Section */}
      <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
        Security
      </Typography>
      
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Controller
            name='password'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='Password'
                type={showPassword ? 'text' : 'password'}
                error={!!errors.password}
                helperText={errors.password?.message || 'Password must be at least 12 characters'}
                disabled={isSubmitting}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position='end'>
                      <IconButton onClick={() => setShowPassword(!showPassword)} edge='end'>
                        <Icon icon={showPassword ? 'tabler:eye-off' : 'tabler:eye'} fontSize={20} />
                      </IconButton>
                    </InputAdornment>
                  )
                }}
              />
            )}
          />
        </Grid>

        <Grid item xs={12}>
          <Controller
            name='confirmPassword'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='Confirm Password'
                type={showConfirmPassword ? 'text' : 'password'}
                error={!!errors.confirmPassword}
                helperText={errors.confirmPassword?.message}
                disabled={isSubmitting}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position='end'>
                      <IconButton onClick={() => setShowConfirmPassword(!showConfirmPassword)} edge='end'>
                        <Icon icon={showConfirmPassword ? 'tabler:eye-off' : 'tabler:eye'} fontSize={20} />
                      </IconButton>
                    </InputAdornment>
                  )
                }}
              />
            )}
          />
        </Grid>
      </Grid>

      <Button
        type='submit'
        fullWidth
        variant='contained'
        size='large'
        disabled={isSubmitting}
        sx={{ mt: 4, py: 1.2, borderRadius: 2, textTransform: 'none', fontWeight: 600 }}
      >
        {isSubmitting ? <CircularProgress size={24} color="inherit" /> : 'Create Account'}
      </Button>
    </form>
  )
}

export default IndividualRegister