// // BusinessRegister.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 Typography from '@mui/material/Typography'
// import Grid from '@mui/material/Grid'
// import MenuItem from '@mui/material/MenuItem'
// import InputAdornment from '@mui/material/InputAdornment'
// import IconButton from '@mui/material/IconButton'
// import Checkbox from '@mui/material/Checkbox'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Alert from '@mui/material/Alert'
// import CircularProgress from '@mui/material/CircularProgress'
// import Box from '@mui/material/Box'
// 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 BusinessFormData {
//   companyName: string
//   businessType: string
//   taxId: string
//   firstName: string
//   lastName: string
//   email: string
//   phoneCode: string
//   phoneNumber: string
//   businessAddress: string
//   city: string
//   state: string
//   zipCode: string
//   country: string
//   website: string
//   password: string
//   confirmPassword: string
//   agreeTerms: boolean
// }

// const businessTypes = [
//   'Sole Proprietorship',
//   'Partnership',
//   'Limited Liability Company (LLC)',
//   'Corporation (C-Corp)',
//   'Corporation (S-Corp)',
//   'Non-Profit Organization'
// ]

// const schema = yup.object().shape({
//   companyName: yup.string().required('Company name is required'),
//   businessType: yup.string().required('Business type is required'),
//   taxId: yup.string().required('Tax ID is required'),
//   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'),
//   businessAddress: yup.string().required('Business 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'),
//   website: yup.string().url('Invalid URL'),
//   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'),
//   agreeTerms: yup.boolean().oneOf([true], 'You must accept the terms')
// })

// const BusinessRegister = () => {
//   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<BusinessFormData>({
//     mode: 'onBlur',
//     resolver: yupResolver(schema),
//     defaultValues: {
//       phoneCode: '+1'
//     }
//   })

//   const onSubmit = async (data: BusinessFormData) => {
//     setIsSubmitting(true)
//     setSubmitError(null)
    
//     const completeData = { 
//       ...data, 
//       phone: `${data.phoneCode} ${data.phoneNumber}`,
//       fullName: `${data.firstName} ${data.lastName}`,
//       type: 'business', 
//       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)}>
//       {/* Company Information Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
//         Business Details
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='companyName'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Company Name'
//                 placeholder='Acme Inc.'
//                 error={!!errors.companyName}
//                 helperText={errors.companyName?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='businessType'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 select
//                 fullWidth
//                 label='Business Type'
//                 error={!!errors.businessType}
//                 helperText={errors.businessType?.message}
//                 disabled={isSubmitting}
//               >
//                 <MenuItem value='' disabled>Select business type</MenuItem>
//                 {businessTypes.map(type => (
//                   <MenuItem key={type} value={type}>{type}</MenuItem>
//                 ))}
//               </TextField>
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='taxId'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='TIN / Tax ID / EIN'
//                 placeholder='XX-XXXXXXX'
//                 error={!!errors.taxId}
//                 helperText={errors.taxId?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Contact Person Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//        Owner Contact Person
//       </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} sm={6}>
//           <Controller
//             name='email'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 type='email'
//                 label='Email Address'
//                 placeholder='contact@company.com'
//                 error={!!errors.email}
//                 helperText={errors.email?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={6}>
//           <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>

//       {/* Business Address Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Business Address
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='businessAddress'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Street Address'
//                 placeholder='123 Business Blvd'
//                 error={!!errors.businessAddress}
//                 helperText={errors.businessAddress?.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 item xs={12}>
//           <Controller
//             name='website'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Website Link'
//                 placeholder='https://www.company.com'
//                 error={!!errors.website}
//                 helperText={errors.website?.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 item xs={12}>
//           <Controller
//             name='agreeTerms'
//             control={control}
//             render={({ field }) => (
//               <FormControlLabel
//                 control={
//                   <Checkbox
//                     checked={field.value}
//                     onChange={field.onChange}
//                     disabled={isSubmitting}
//                   />
//                 }
//                 label={
//                   <Typography variant="body2">
//                     I agree to the{' '}
//                     <a href="#" style={{ color: '#1976d2', textDecoration: 'none' }}>
//                       Terms of Service
//                     </a>{' '}
//                     and{' '}
//                     <a href="#" style={{ color: '#1976d2', textDecoration: 'none' }}>
//                       Privacy Policy
//                     </a>
//                   </Typography>
//                 }
//               />
//             )}
//           />
//           {errors.agreeTerms && (
//             <Typography color="error" variant="caption" sx={{ mt: 0.5, display: 'block' }}>
//               {errors.agreeTerms.message}
//             </Typography>
//           )}
//         </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 Business Account'}
//       </Button>
//     </form>
//   )
// }

// export default BusinessRegister


// BusinessRegister.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 Typography from '@mui/material/Typography'
// import Grid from '@mui/material/Grid'
// import MenuItem from '@mui/material/MenuItem'
// import InputAdornment from '@mui/material/InputAdornment'
// import IconButton from '@mui/material/IconButton'
// import Checkbox from '@mui/material/Checkbox'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Alert from '@mui/material/Alert'
// import CircularProgress from '@mui/material/CircularProgress'
// import Box from '@mui/material/Box'
// 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'
// import { useMutation } from '@tanstack/react-query'
// import toast from 'react-hot-toast'

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

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

// // ** Axios Instance
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

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

// interface BusinessFormData {
//   companyName: string
//   businessType: string
//   taxId: string
//   firstName: string
//   lastName: string
//   email: string
//   phoneCode: string
//   phoneNumber: string
//   businessAddress: string
//   city: string
//   state: string
//   zipCode: string
//   country: string
//   website: string
//   password: string
//   confirmPassword: string
//   agreeTerms: boolean
// }

// const businessTypes = [
//   'Sole Proprietorship',
//   'Partnership',
//   'Limited Liability Company (LLC)',
//   'Corporation (C-Corp)',
//   'Corporation (S-Corp)',
//   'Non-Profit Organization'
// ]

// const schema = yup.object().shape({
//   companyName: yup.string().required('Company name is required'),
//   businessType: yup.string().required('Business type is required'),
//   taxId: yup.string().required('Tax ID is required'),
//   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'),
//   businessAddress: yup.string().required('Business 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'),
//   website: yup.string().url('Invalid URL'),
//   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'),
//   agreeTerms: yup.boolean().oneOf([true], 'You must accept the terms')
// })

// // AES Encryption function
// const encryptAES = (text: 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)
// }

// // API call function for Business
// const registerBusiness = async (data: any) => {
//   const response = await axios.post(endpoints.auth.register, data)
//   return response.data
// }

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

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

//   const { mutate, isPending } = useMutation({
//     mutationFn: registerBusiness,
//     onSuccess: (response) => {
//       toast.success('Business registration successful! Please verify your account.')
//       localStorage.setItem('registerData', JSON.stringify(response))
//       setTimeout(() => {
//         router.push('/verify-account')
//       }, 1500)
//     },
//     onError: (err: any) => {
//       const status = err?.response?.status
//       const message = err?.response?.data?.content || err?.response?.data?.message || 'Registration failed. Please try again.'
      
//       if ([400, 401, 403, 409].includes(status)) {
//         setSubmitError(message)
//         toast.error(message)
//       } else {
//         setSubmitError('Something went wrong. Please try again later.')
//         toast.error('Registration failed')
//       }
      
//       console.error('Business Registration Error:', err)
//     }
//   })

//   const onSubmit = async (data: BusinessFormData) => {
//     setSubmitError(null)
    
//     // Find country code from countries list
//     const selectedCountry = countries.find(c => c.phone === data.phoneCode)
//     const countryCode = selectedCountry?.code || 'US'
    
//     // Encrypt password
//     const encryptedPassword = encryptAES(data.password)
    
//     // Prepare payload for API
//     const payload = {
//       firstName: data.firstName,
//       lastName: data.lastName,
//       emailId: data.email,
//       mobileNumber: data.phoneNumber.replace(/\s/g, ''),
//       countryCode: countryCode,
//       dialCountryCode: data.phoneCode,
//       address: data.businessAddress,
//       city: data.city,
//       state: data.state,
//       country: data.country,
//       password: encryptedPassword,
//       confirmPassword: encryptedPassword,
//       userAccountType: "Business",
//       companyName: data.companyName,
//       businessType: data.businessType,
//       taxId: data.taxId,
//       website: data.website || '',
//       agreeTerms: data.agreeTerms
//     }
    
//     mutate(payload)
//   }

//   return (
//     <form onSubmit={handleSubmit(onSubmit)}>
//       {/* Company Information Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, color: 'primary.main' }}>
//         Company Information
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='companyName'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Company Name'
//                 placeholder='Acme Inc.'
//                 error={!!errors.companyName}
//                 helperText={errors.companyName?.message}
//                 disabled={isPending}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='businessType'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 select
//                 fullWidth
//                 label='Business Type'
//                 error={!!errors.businessType}
//                 helperText={errors.businessType?.message}
//                 disabled={isPending}
//               >
//                 <MenuItem value='' disabled>Select business type</MenuItem>
//                 {businessTypes.map(type => (
//                   <MenuItem key={type} value={type}>{type}</MenuItem>
//                 ))}
//               </TextField>
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='taxId'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Tax ID / EIN'
//                 placeholder='XX-XXXXXXX'
//                 error={!!errors.taxId}
//                 helperText={errors.taxId?.message}
//                 disabled={isPending}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Contact Person Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Contact Person
//       </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={isPending}
//               />
//             )}
//           />
//         </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={isPending}
//               />
//             )}
//           />
//         </Grid>

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

//         <Grid item xs={12} sm={6}>
//           <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={isPending}
//                           inputProps={{
//                             ...params.inputProps,
//                             autoComplete: 'new-password',
//                           }}
//                         />
//                       )}
//                     />
//                     <TextField
//                       {...phoneNumberField}
//                       fullWidth
//                       label='Phone Number'
//                       placeholder='555 000 0000'
//                       error={!!errors.phoneNumber}
//                       helperText={errors.phoneNumber?.message}
//                       disabled={isPending}
//                     />
//                   </Box>
//                 )}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Business Address Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Business Address
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='businessAddress'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Street Address'
//                 placeholder='123 Business Blvd'
//                 error={!!errors.businessAddress}
//                 helperText={errors.businessAddress?.message}
//                 disabled={isPending}
//               />
//             )}
//           />
//         </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={isPending}
//               />
//             )}
//           />
//         </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={isPending}
//               />
//             )}
//           />
//         </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={isPending}
//               />
//             )}
//           />
//         </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={isPending}
//                   />
//                 )}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='website'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Website (Optional)'
//                 placeholder='https://www.company.com'
//                 error={!!errors.website}
//                 helperText={errors.website?.message}
//                 disabled={isPending}
//               />
//             )}
//           />
//         </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={isPending}
//                 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={isPending}
//                 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 item xs={12}>
//           <Controller
//             name='agreeTerms'
//             control={control}
//             render={({ field }) => (
//               <FormControlLabel
//                 control={
//                   <Checkbox
//                     checked={field.value}
//                     onChange={field.onChange}
//                     disabled={isPending}
//                   />
//                 }
//                 label={
//                   <Typography variant="body2">
//                     I agree to the{' '}
//                     <a href="#" style={{ color: '#1976d2', textDecoration: 'none' }}>
//                       Terms of Service
//                     </a>{' '}
//                     and{' '}
//                     <a href="#" style={{ color: '#1976d2', textDecoration: 'none' }}>
//                       Privacy Policy
//                     </a>
//                   </Typography>
//                 }
//               />
//             )}
//           />
//           {errors.agreeTerms && (
//             <Typography color="error" variant="caption" sx={{ mt: 0.5, display: 'block' }}>
//               {errors.agreeTerms.message}
//             </Typography>
//           )}
//         </Grid>
//       </Grid>

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

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

// export default BusinessRegister


// 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 Typography from '@mui/material/Typography'
// import Grid from '@mui/material/Grid'
// import InputAdornment from '@mui/material/InputAdornment'
// import IconButton from '@mui/material/IconButton'
// import Checkbox from '@mui/material/Checkbox'
// import FormControlLabel from '@mui/material/FormControlLabel'
// import Alert from '@mui/material/Alert'
// import CircularProgress from '@mui/material/CircularProgress'
// import Box from '@mui/material/Box'
// 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'
// import toast from 'react-hot-toast'

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

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

// // ** Axios Instance
// import axios from 'src/configs/axios'
// import endpoints from 'src/configs/endpoints'

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

// interface BusinessFormData {
//   companyName: string
//   businessType: string
//   einNumber: string
//   firstName: string
//   lastName: string
//   email: string
//   phoneCode: string
//   dialCountryCode: string
//   phoneNumber: string
//   address: string
//   city: string
//   state: string
//   postalCode: string
//   country: string
//   websiteLink: string
//   password: string
//   confirmPassword: string
//   agreeTerms: boolean
// }

// const schema = yup.object().shape({
//   companyName: yup.string().required('Company name is required'),
//   businessType: yup.string().required('Business type is required'),
//   einNumber: yup.string().required('EIN number is required'),
//   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'),
//   address: yup.string().required('Business address is required'),
//   city: yup.string().required('City is required'),
//   state: yup.string().required('State is required'),
//   postalCode: yup.string().required('Postal code is required'),
//   country: yup.string().required('Country is required'),
//   websiteLink: yup.string().url('Invalid URL'),
//   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'),
//   agreeTerms: yup.boolean().oneOf([true], 'You must accept the terms')
// })

// // AES Encryption function
// const encryptAES = (text: 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)
// }

// const BusinessRegister = () => {
//   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 },
//     setValue,
//     watch
//   } = useForm<BusinessFormData>({
//     mode: 'onBlur',
//     resolver: yupResolver(schema),
//     defaultValues: {
//       phoneCode: 'US',
//       dialCountryCode: '+1',
//       businessType: '',
//       einNumber: '',
//       websiteLink: '',
//       agreeTerms: false
//     }
//   })

//   const selectedPhoneCode = watch('phoneCode')

//   const onSubmit = async (data: BusinessFormData) => {
//     setIsSubmitting(true)
//     setSubmitError(null)
    
//     try {
//       // Encrypt password
//       const encryptedPassword = encryptAES(data.password)
//       const encryptedConfirmPassword = encryptAES(data.confirmPassword)
      
//       // Prepare payload for API matching the exact structure
//       const payload = {
//         firstName: data.firstName,
//         lastName: data.lastName,
//         emailId: data.email,
//         mobileNumber: data.phoneNumber.replace(/\s/g, ''),
//         countryCode: data.dialCountryCode, // This should be the dial code like "+91"
//         dialCountryCode: data.phoneCode,    // This should be the country code like "IN"
//         address: data.address,
//         city: data.city,
//         state: data.state,
//         country: data.country,
//         postalCode: data.postalCode,
//         password: encryptedPassword,
//         confirmPassword: encryptedConfirmPassword,
//         userAccountType: "Business",
//         companyName: data.companyName,
//         businessType: data.businessType,
//         einNumber: data.einNumber,
//         websiteLink: data.websiteLink || ""
//       }
      
//       console.log('Submitting Business Registration:', payload)
      
//       // Call the API
//       const response = await axios.post(endpoints.auth.register, payload)
      
//       console.log('Business Registration Response:', response.data)
      
//       // Check if registration was successful
//       if (response.data && (response.data.status === 'success' || response.data.success || response.status === 200 || response.status === 201)) {
//         toast.success('Business registration successful! Please verify your account.')
        
//         // Store email for verification page
//         localStorage.setItem('registerEmail', data.email)
        
//         // Store token if received
//         if (response.data.token) {
//           localStorage.setItem('accessToken', response.data.token)
//         }
        
//         // Store registration data if needed
//         localStorage.setItem('registerData', JSON.stringify(response.data))
        
//         // Redirect to verify account page
//         setTimeout(() => {
//           router.push('/verify-account')
//         }, 1500)
//       } else {
//         const errorMessage = response.data?.message || response.data?.error || 'Registration failed. Please try again.'
//         setSubmitError(errorMessage)
//         toast.error(errorMessage)
//       }
      
//     } catch (error: any) {
//       console.error('Business Registration Error:', error)
      
//       // Handle different error scenarios
//       if (error.response) {
//         const status = error.response.status
//         const errorData = error.response.data
        
//         if (status === 400) {
//           const message = errorData?.message || 'Invalid data provided. Please check your information.'
//           setSubmitError(message)
//           toast.error(message)
//         } else if (status === 409) {
//           const message = 'User with this email already exists. Please use a different email or login.'
//           setSubmitError(message)
//           toast.error(message)
//         } else if (status === 500) {
//           const message = 'Server error. Please try again later.'
//           setSubmitError(message)
//           toast.error(message)
//         } else {
//           const message = errorData?.message || errorData?.error || 'Registration failed. Please try again.'
//           setSubmitError(message)
//           toast.error(message)
//         }
//       } else if (error.request) {
//         const message = 'Network error. Please check your internet connection and try again.'
//         setSubmitError(message)
//         toast.error(message)
//       } else {
//         const message = 'An unexpected error occurred. Please try again.'
//         setSubmitError(message)
//         toast.error(message)
//       }
//     } finally {
//       setIsSubmitting(false)
//     }
//   }

//   // Helper function to get country by phone code
//   const getSelectedCountry = () => {
//     return countries.find(c => c.code === selectedPhoneCode) || null
//   }

//   // Handle country code selection
//   const handleCountryCodeChange = (country: any) => {
//     if (country) {
//       setValue('phoneCode', country.code)
//       setValue('dialCountryCode', `+${country.phone}`)
//     }
//   }

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

//         <Grid item xs={12}>
//           <Controller
//             name='businessType'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Business Type'
//                 placeholder='C corporation'
//                 error={!!errors.businessType}
//                 helperText={errors.businessType?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='einNumber'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='EIN Number'
//                 placeholder='123456789'
//                 error={!!errors.einNumber}
//                 helperText={errors.einNumber?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Contact Person Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Contact Person
//       </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} sm={6}>
//           <Controller
//             name='email'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 type='email'
//                 label='Email Address'
//                 placeholder='john.doe@gmail.com'
//                 error={!!errors.email}
//                 helperText={errors.email?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='phoneNumber'
//             control={control}
//             render={({ field: phoneNumberField }) => (
//               <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
//                 <Controller
//                   name='phoneCode'
//                   control={control}
//                   render={({ field: phoneCodeField }) => (
//                     <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='Mobile Number'
//                   placeholder='9876543210'
//                   error={!!errors.phoneNumber}
//                   helperText={errors.phoneNumber?.message}
//                   disabled={isSubmitting}
//                 />
//               </Box>
//             )}
//           />
//         </Grid>
//       </Grid>

//       {/* Business Address Section */}
//       <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
//         Business Address
//       </Typography>
      
//       <Grid container spacing={3}>
//         <Grid item xs={12}>
//           <Controller
//             name='address'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Street Address'
//                 placeholder='xyz road'
//                 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='Nashik'
//                 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='Maharashtra'
//                 error={!!errors.state}
//                 helperText={errors.state?.message}
//                 disabled={isSubmitting}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='postalCode'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Postal Code'
//                 placeholder='12345'
//                 error={!!errors.postalCode}
//                 helperText={errors.postalCode?.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='India'
//                     error={!!errors.country}
//                     helperText={errors.country?.message}
//                     disabled={isSubmitting}
//                   />
//                 )}
//               />
//             )}
//           />
//         </Grid>

//         <Grid item xs={12}>
//           <Controller
//             name='websiteLink'
//             control={control}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 label='Website Link (Optional)'
//                 placeholder='http://abc.com'
//                 error={!!errors.websiteLink}
//                 helperText={errors.websiteLink?.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 item xs={12}>
//           <Controller
//             name='agreeTerms'
//             control={control}
//             render={({ field }) => (
//               <FormControlLabel
//                 control={
//                   <Checkbox
//                     checked={field.value}
//                     onChange={field.onChange}
//                     disabled={isSubmitting}
//                   />
//                 }
//                 label={
//                   <Typography variant="body2">
//                     I agree to the{' '}
//                     <a href="#" style={{ color: '#1976d2', textDecoration: 'none' }}>
//                       Terms of Service
//                     </a>{' '}
//                     and{' '}
//                     <a href="#" style={{ color: '#1976d2', textDecoration: 'none' }}>
//                       Privacy Policy
//                     </a>
//                   </Typography>
//                 }
//               />
//             )}
//           />
//           {errors.agreeTerms && (
//             <Typography color="error" variant="caption" sx={{ mt: 0.5, display: 'block' }}>
//               {errors.agreeTerms.message}
//             </Typography>
//           )}
//         </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 Business Account'}
//       </Button>
//     </form>
//   )
// }

// export default BusinessRegister

// 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 Typography from '@mui/material/Typography'
import Grid from '@mui/material/Grid'
import InputAdornment from '@mui/material/InputAdornment'
import IconButton from '@mui/material/IconButton'
import Checkbox from '@mui/material/Checkbox'
import FormControlLabel from '@mui/material/FormControlLabel'
import CircularProgress from '@mui/material/CircularProgress'
import Box from '@mui/material/Box'
import Autocomplete from '@mui/material/Autocomplete'
import MenuItem from '@mui/material/MenuItem'
import Select from '@mui/material/Select'
import FormControl from '@mui/material/FormControl'
import InputLabel from '@mui/material/InputLabel'
import FormHelperText from '@mui/material/FormHelperText'

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

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

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

// ** Axios Instance
import axios from 'src/configs/axios'
import endpoints from 'src/configs/endpoints'

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

interface BusinessFormData {
  companyName: string
  businessType: string
  businessTypeOther?: string
  einNumber: string
  firstName: string
  lastName: string
  email: string
  phoneCode: string
  dialCountryCode: string
  phoneNumber: string
  address: string
  city: string
  state: string
  postalCode: string
  country: string
  websiteLink: string
  password: string
  confirmPassword: string
  agreeTerms: boolean
  ssn: string
}

// Business type options
const BUSINESS_TYPES = [
  'Limited Partnership',
  'General Partnership',
  'S Corporation',
  'C Corporation',
  'Sole Proprietorship',
  'Other'
]

// Updated validation schema with EIN format and SSN
const schema = yup.object().shape({
  companyName: yup.string().required('Company name is required'),
  businessType: yup.string().required('Business type is required'),
  businessTypeOther: yup.string().when('businessType', {
    is: 'Other',
    then: yup.string().required('Please specify your business type'),
    otherwise: yup.string().notRequired()
  }),
  einNumber: yup.string()
    .required('EIN number is required')
    .matches(/^\d{2}-\d{7}$/, 'EIN must be in format XX-XXXXXXX'),
  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'),
  address: yup.string().required('Business address is required'),
  city: yup.string().required('City is required'),
  state: yup.string().required('State is required'),
  postalCode: yup.string().required('Postal code is required'),
  country: yup.string().required('Country is required'),
  websiteLink: yup.string().url('Invalid URL'),
  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'),
  agreeTerms: yup.boolean().oneOf([true], 'You must accept the terms'),
  ssn: yup.string().matches(/^\d{3}-\d{3}-\d{3}$/, 'SSN must be in format XXX-XXX-XXX').required('SSN is required')
})

// 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)
}

// 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 = [
    /^companyName\s*/i,
    /^businessType\s*/i,
    /^businessTypeOther\s*/i,
    /^einNumber\s*/i,
    /^firstName\s*/i,
    /^lastName\s*/i,
    /^email\s*/i,
    /^phoneCode\s*/i,
    /^phoneNumber\s*/i,
    /^address\s*/i,
    /^city\s*/i,
    /^state\s*/i,
    /^postalCode\s*/i,
    /^country\s*/i,
    /^websiteLink\s*/i,
    /^password\s*/i,
    /^confirmPassword\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('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') ||
       cleanMessage.toLowerCase().includes('company name') ||
       cleanMessage.toLowerCase().includes('ein') ||
       cleanMessage.toLowerCase().includes('business type'))) {
    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 EIN with masking - XX-XXXXXXX format
const formatEIN = (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 dash - XX-XXXXXXX
  let formatted = ''
  for (let i = 0; i < limited.length; i++) {
    if (i === 2) {
      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
}

const BusinessRegister = () => {
  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)

  // Refs for input fields
  const einInputRef = useRef<HTMLInputElement>(null)
  const ssnInputRef = useRef<HTMLInputElement>(null)

  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    watch
  } = useForm<BusinessFormData>({
    mode: 'onBlur',
    resolver: yupResolver(schema),
    defaultValues: {
      phoneCode: 'US',
      dialCountryCode: '+1',
      businessType: '',
      businessTypeOther: '',
      einNumber: '',
      websiteLink: '',
      agreeTerms: false,
      ssn: ''
    }
  })

  const selectedPhoneCode = watch('phoneCode')
  const businessType = watch('businessType')

  // Handle EIN input change
  const handleEINChange = (e: React.ChangeEvent<HTMLInputElement>, onChange: (value: string) => void) => {
    const rawValue = e.target.value
    const formatted = formatEIN(rawValue)
    
    // Update the form state
    onChange(formatted)
    
    // Update the input value directly
    if (einInputRef.current) {
      einInputRef.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 onSubmit = async (data: BusinessFormData) => {
    setIsSubmitting(true)
    setSubmitError(null)
    
    try {
      // Encrypt password and confirmPassword
      const encryptedPassword = encryptAES(data.password)
      const encryptedConfirmPassword = encryptAES(data.confirmPassword)
      
      // Clean phone number
      const cleanPhoneNumber = data.phoneNumber.replace(/\s/g, '')
      
      // Determine business type value to send to API
      let businessTypeValue = data.businessType
      if (data.businessType === 'Other' && data.businessTypeOther) {
        businessTypeValue = data.businessTypeOther
      }
      
      // Prepare API request body
      const requestBody = {
        firstName: data.firstName,
        lastName: data.lastName,
        emailId: data.email,
        mobileNumber: cleanPhoneNumber,
        countryCode: data.dialCountryCode,
        dialCountryCode: data.phoneCode,
        address: data.address,
        city: data.city,
        state: data.state,
        country: data.country,
        password: encryptedPassword,
        confirmPassword: encryptedConfirmPassword,
        userAccountType: "Business",
        companyName: data.companyName,
        businessType: businessTypeValue,
        einNumber: data.einNumber,
        websiteLink: data.websiteLink || "",
        ssn: data.ssn,
        postalCode: data.postalCode
      }
      
      // 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('Business account created successfully! Please verify your email.')
        
        if (response.data.token) {
          localStorage.setItem('accessToken', response.data.token)
        }
        
        localStorage.setItem('registerEmail', data.email)
        
        // Redirect to login page
        setTimeout(() => {
          router.push('/login')
        }, 1500)
      } else {
        // Handle unexpected success response
        const errorMessage = response.data?.message || 'Registration failed. Please try again.'
        setSubmitError(errorMessage)
        toast.error(errorMessage)
      }
      
    } catch (error: any) {
      console.error('Business 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
          const hasFieldErrors = Object.keys(errorData).some(key => 
            typeof errorData[key] === 'string' && 
            (key === 'firstName' || key === 'lastName' || key === 'email' || 
             key === 'password' || key === 'ssn' || key === 'phoneNumber' ||
             key === 'companyName' || key === 'einNumber' || key === 'businessType')
          )
          
          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)
            setSubmitError(errorMessage)
            toast.error(errorMessage)
          } 

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

          // Check for detail field
          else if (errorData.detail) {
            const errorMessage = mapBackendErrorToMessage(errorData.detail)
            setSubmitError(errorMessage)
            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
            const genericMessage = 'Registration failed. Please check your information and try again.'
            setSubmitError(genericMessage)
            toast.error(genericMessage)
          }
        } else {
          // If errorData is not an object, pass it to mapBackendErrorToMessage
          const errorMessage = mapBackendErrorToMessage(errorData)
          setSubmitError(errorMessage)
          toast.error(errorMessage)
        }
      } else if (error?.message) {
        const errorMessage = error.message
        setSubmitError(errorMessage)
        toast.error(errorMessage)
      } else {
        const errorMessage = 'Registration failed. Please check your connection and try again.'
        setSubmitError(errorMessage)
        toast.error(errorMessage)
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  // Helper function to get country by phone code
  const getSelectedCountry = () => {
    return countries.find(c => c.code === selectedPhoneCode) || null
  }

  // Handle country code selection
  const handleCountryCodeChange = (country: any) => {
    if (country) {
      setValue('phoneCode', country.code)
      setValue('dialCountryCode', `+${country.phone}`)
    }
  }

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

        <Grid item xs={12}>
          <Controller
            name='businessType'
            control={control}
            render={({ field }) => (
              <FormControl fullWidth error={!!errors.businessType}>
                <InputLabel id="business-type-label">Business Type</InputLabel>
                <Select
                  {...field}
                  labelId="business-type-label"
                  label="Business Type"
                  disabled={isSubmitting}
                  value={field.value || ''}
                  onChange={(e) => {
                    field.onChange(e.target.value)

                    // Clear the other business type field when changing selection
                    if (e.target.value !== 'Other') {
                      setValue('businessTypeOther', '')
                    }
                  }}
                >
                  {BUSINESS_TYPES.map((type) => (
                    <MenuItem key={type} value={type}>
                      {type}
                    </MenuItem>
                  ))}
                </Select>
                {errors.businessType && (
                  <FormHelperText>{errors.businessType.message}</FormHelperText>
                )}
              </FormControl>
            )}
          />
        </Grid>

        {/* Show Other Business Type Text Field when "Other" is selected */}
        {businessType === 'Other' && (
          <Grid item xs={12}>
            <Controller
              name='businessTypeOther'
              control={control}
              render={({ field }) => (
                <TextField
                  {...field}
                  fullWidth
                  label='Please specify your business type'
                  placeholder='Enter your business type'
                  error={!!errors.businessTypeOther}
                  helperText={errors.businessTypeOther?.message}
                  disabled={isSubmitting}
                />
              )}
            />
          </Grid>
        )}

        <Grid item xs={12}>
          <Controller
            name='einNumber'
            control={control}
            render={({ field }) => (
              <TextField
                inputRef={einInputRef}
                {...field}
                fullWidth
                label='EIN Number'
                placeholder='XX-XXXXXXX'
                helperText={errors.einNumber?.message || 'Format: XX-XXXXXXX'}
                error={!!errors.einNumber}
                disabled={isSubmitting}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleEINChange(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 = formatEIN(cleaned)
                  field.onChange(formatted)
                  if (einInputRef.current) {
                    einInputRef.current.value = formatted
                  }
                }}
                inputProps={{
                  maxLength: 10,
                  autoComplete: 'off'
                }}
              />
            )}
          />
        </Grid>
      </Grid>

      {/* Contact Person Section */}
      <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
        Contact Person
      </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} sm={6}>
          <Controller
            name='email'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                type='email'
                label='Email Address'
                placeholder='john.doe@gmail.com'
                error={!!errors.email}
                helperText={errors.email?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>

        <Grid item xs={12} sm={6}>
          <Controller
            name='phoneNumber'
            control={control}
            render={({ field: phoneNumberField }) => (
              <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
                <Controller
                  name='phoneCode'
                  control={control}
                  render={({ field: phoneCodeField }) => (
                    <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='Mobile Number'
                  placeholder='9876543210'
                  error={!!errors.phoneNumber}
                  helperText={errors.phoneNumber?.message}
                  disabled={isSubmitting}
                />
              </Box>
            )}
          />
        </Grid>

        {/* SSN Field */}
        <Grid item xs={12}>
          <Controller
            name='ssn'
            control={control}
            render={({ field }) => (
              <TextField
                inputRef={ssnInputRef}
                fullWidth
                label='SSN/ITIN/TIN(Optional)'
                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>

      {/* Business Address Section */}
      <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2, mt: 4, color: 'primary.main' }}>
        Business Address
      </Typography>
      
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Controller
            name='address'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='Street Address'
                placeholder='xyz road'
                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='Nashik'
                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='Maharashtra'
                error={!!errors.state}
                helperText={errors.state?.message}
                disabled={isSubmitting}
              />
            )}
          />
        </Grid>

        <Grid item xs={12} sm={4}>
          <Controller
            name='postalCode'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='Postal Code'
                placeholder='12345'
                error={!!errors.postalCode}
                helperText={errors.postalCode?.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='India'
                    error={!!errors.country}
                    helperText={errors.country?.message}
                    disabled={isSubmitting}
                  />
                )}
              />
            )}
          />
        </Grid>

        <Grid item xs={12}>
          <Controller
            name='websiteLink'
            control={control}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                label='Website Link (Optional)'
                placeholder='http://abc.com'
                error={!!errors.websiteLink}
                helperText={errors.websiteLink?.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 item xs={12}>
          <Controller
            name='agreeTerms'
            control={control}
            render={({ field }) => (
              <FormControlLabel
                control={
                  <Checkbox
                    checked={field.value}
                    onChange={field.onChange}
                    disabled={isSubmitting}
                  />
                }
                label={
                  <Typography variant="body2">
                    I agree to the{' '}
                    <a href="#" style={{ color: '#1976d2', textDecoration: 'none' }}>
                      Terms of Service
                    </a>{' '}
                    and{' '}
                    <a href="#" style={{ color: '#1976d2', textDecoration: 'none' }}>
                      Privacy Policy
                    </a>
                  </Typography>
                }
              />
            )}
          />
          {errors.agreeTerms && (
            <Typography color="error" variant="caption" sx={{ mt: 0.5, display: 'block' }}>
              {errors.agreeTerms.message}
            </Typography>
          )}
        </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 Business Account'}
      </Button>
    </form>
  )
}

export default BusinessRegister
