// import React from 'react'
// import { useForm, Controller, SubmitHandler } from 'react-hook-form'
// import { Grid, TextField, Button } from '@mui/material'

// // ** Customer Props Types

// type CustomerFormProps = {
//   storeCustomerData: (data: { name: string; id: number }) => void
// }

// // ** Form Value Types
// type FormValues = {
//   customerName: string
//   phone: string
//   email?: string
//   address?: string
//   city?: string
//   country?: string
// }

// const CustomerForm: React.FC<CustomerFormProps> = props => {
//   const {
//     handleSubmit,
//     control,
//     formState: { errors }
//   } = useForm<FormValues>({
//     defaultValues: {
//       customerName: '',
//       phone: '',
//       email: '',
//       address: '',
//       city: '',
//       country: ''
//     }
//   })

//   const onSubmit: SubmitHandler<FormValues> = data => {
//     props.storeCustomerData({ name: data.customerName, id: 0 })
//   }

//   return (
//     <form onSubmit={handleSubmit(onSubmit)}>
//       <Grid container spacing={2}>
//         {/* Customer Name */}
//         <Grid item sx={{ mb: 2 }} xs={12} sm={6}>
//           <Controller
//             name='customerName'
//             control={control}
//             rules={{ required: 'Customer Name is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 label='Customer Name'
//                 fullWidth
//                 error={!!errors.customerName}
//                 helperText={errors.customerName?.message}
//               />
//             )}
//           />
//         </Grid>

//         {/* Phone */}
//         <Grid item sx={{ mb: 2 }} xs={12} sm={6}>
//           <Controller
//             name='phone'
//             control={control}
//             rules={{
//               required: 'Phone is required',
//               pattern: { value: /^[0-9]+$/, message: 'Only numbers allowed' }
//             }}
//             render={({ field }) => (
//               <TextField {...field} label='Phone' fullWidth error={!!errors.phone} helperText={errors.phone?.message} />
//             )}
//           />
//         </Grid>

//         {/* Email */}
//         <Grid item sx={{ mb: 2 }} xs={12}>
//           <Controller
//             name='email'
//             control={control}
//             rules={{
//               pattern: {
//                 value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
//                 message: 'Invalid email address'
//               }
//             }}
//             render={({ field }) => (
//               <TextField {...field} label='Email' fullWidth error={!!errors.email} helperText={errors.email?.message} />
//             )}
//           />
//         </Grid>

//         {/* Address */}
//         <Grid item sx={{ mb: 2 }} xs={12}>
//           <Controller
//             name='address'
//             control={control}
//             render={({ field }) => <TextField {...field} label='Address' fullWidth />}
//           />
//         </Grid>

//         {/* City */}
//         <Grid item sx={{ mb: 2 }} xs={12} sm={6}>
//           <Controller
//             name='city'
//             control={control}
//             render={({ field }) => <TextField {...field} label='City' fullWidth />}
//           />
//         </Grid>

//         {/* Country */}
//         <Grid item sx={{ mb: 2 }} xs={12} sm={6}>
//           <Controller
//             name='country'
//             control={control}
//             render={({ field }) => <TextField {...field} label='Country' fullWidth />}
//           />
//         </Grid>

//         {/* Submit Button */}
//         <Grid item sx={{ mb: 2, borderTop: theme => `1px solid ${theme.palette.divider}` }} xs={12}>
//           <Button type='submit' variant='contained' color='primary'>
//             Submit
//           </Button>
//           <Button type='reset' variant='contained' color='secondary' sx={{ ml: 2 }}>
//             Cancel
//           </Button>
//         </Grid>
//       </Grid>
//     </form>
//   )
// }

// export default CustomerForm


// sagar changes //////////////////
// import React from 'react'

// // ** MUI Imports
// import Grid from '@mui/material/Grid'
// import TextField from '@mui/material/TextField'
// import Button from '@mui/material/Button'
// import Box from '@mui/material/Box'

// // ** React Hook Form
// import { useForm, Controller } from 'react-hook-form'

// // ** Types
// interface CustomerFormData {
//   firstName: string
//   lastName: string
//   emailId: string
//   phoneNumber: string
//   address: string
//   city: string
//   state: string
//   country: string
//   pinCode: string
// }

// interface CustomerFormProps {
//   storeCustomerData: (data: any) => void
//   onClose: () => void
// }

// const CustomerForm: React.FC<CustomerFormProps> = ({ storeCustomerData, onClose }) => {
//   const {
//     control,
//     handleSubmit,
//     formState: { errors }
//   } = useForm<CustomerFormData>({
//     defaultValues: {
//       firstName: '',
//       lastName: '',
//       emailId: '',
//       phoneNumber: '',
//       address: '',
//       city: '',
//       state: '',
//       country: '',
//       pinCode: ''
//     }
//   })

//   const onSubmit = (data: CustomerFormData) => {
//     storeCustomerData(data)
//   }

//   return (
//     <form onSubmit={handleSubmit(onSubmit)}>
//       <Grid container spacing={2} sx={{ pt: 2 }}>
//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='firstName'
//             control={control}
//             rules={{ required: 'First name is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='First Name *'
//                 error={!!errors.firstName}
//                 helperText={errors.firstName?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='lastName'
//             control={control}
//             rules={{ required: 'Last name is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='Last Name *'
//                 error={!!errors.lastName}
//                 helperText={errors.lastName?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='emailId'
//             control={control}
//             rules={{
//               pattern: {
//                 value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
//                 message: 'Invalid email address'
//               }
//             }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='Email'
//                 error={!!errors.emailId}
//                 helperText={errors.emailId?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sm={6}>
//           <Controller
//             name='phoneNumber'
//             control={control}
//             rules={{ required: 'Phone number is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='Phone Number *'
//                 error={!!errors.phoneNumber}
//                 helperText={errors.phoneNumber?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12}>
//           <Controller
//             name='address'
//             control={control}
//             rules={{ required: 'Address is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='Address *'
//                 error={!!errors.address}
//                 helperText={errors.address?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='city'
//             control={control}
//             rules={{ required: 'City is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='City *'
//                 error={!!errors.city}
//                 helperText={errors.city?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='state'
//             control={control}
//             rules={{ required: 'State is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='State *'
//                 error={!!errors.state}
//                 helperText={errors.state?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sm={4}>
//           <Controller
//             name='pinCode'
//             control={control}
//             rules={{ required: 'Zip code is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='Zip Code *'
//                 error={!!errors.pinCode}
//                 helperText={errors.pinCode?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12}>
//           <Controller
//             name='country'
//             control={control}
//             rules={{ required: 'Country is required' }}
//             render={({ field }) => (
//               <TextField
//                 {...field}
//                 fullWidth
//                 size='small'
//                 label='Country *'
//                 error={!!errors.country}
//                 helperText={errors.country?.message}
//               />
//             )}
//           />
//         </Grid>
//         <Grid item xs={12} sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 2 }}>
//           <Button variant='outlined' color='secondary' onClick={onClose}>
//             Cancel
//           </Button>
//           <Button type='submit' variant='contained'>
//             Add Customer
//           </Button>
//         </Grid>
//       </Grid>
//     </form>
//   )
// }

// export default CustomerForm

// country code added 
import React from 'react'

// ** MUI Imports
import Grid from '@mui/material/Grid'
import TextField from '@mui/material/TextField'
import Button from '@mui/material/Button'
import Box from '@mui/material/Box'
import Autocomplete from '@mui/material/Autocomplete'
import Typography from '@mui/material/Typography'

// ** React Hook Form
import { useForm, Controller } from 'react-hook-form'

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

// ** Types
interface CustomerFormData {
  firstName: string
  lastName: string
  emailId: string
  phoneNumber: string
  countryCode: string
  dialCountryCode: string
  address: string
  city: string
  state: string
  country: string
  pinCode: string
}

interface CustomerFormProps {
  storeCustomerData: (data: any) => void
  onClose: () => void
}

const CustomerForm: React.FC<CustomerFormProps> = ({ storeCustomerData, onClose }) => {
  const {
    control,
    handleSubmit,
    setValue,
    watch,
    formState: { errors }
  } = useForm<CustomerFormData>({
    defaultValues: {
      firstName: '',
      lastName: '',
      emailId: '',
      phoneNumber: '',
      countryCode: '+1',
      dialCountryCode: 'US',
      address: '',
      city: '',
      state: '',
      country: '',
      pinCode: ''
    }
  })

  const selectedCountryCode = watch('countryCode')
  const selectedCountry = watch('country')

  // Find US country specifically, not just any country with +1
  const getSelectedCountry = () => {
    if (selectedCountryCode === '+1') {
      // Return US specifically when countryCode is +1
      return countries.find(c => c.code === 'US') || countries.find(c => `+${c.phone}` === selectedCountryCode) || null
    }
    return countries.find(c => `+${c.phone}` === selectedCountryCode) ?? null
  }

  // Get selected country for country field
  const getSelectedCountryField = () => {
    return countries.find(c => c.label === selectedCountry) || null
  }

  const onSubmit = (data: CustomerFormData) => {
    storeCustomerData(data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Grid container spacing={2} sx={{ pt: 2 }}>
        <Grid item xs={12} sm={6}>
          <Controller
            name='firstName'
            control={control}
            rules={{ required: 'First name is required' }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                size='small'
                label='First Name *'
                error={!!errors.firstName}
                helperText={errors.firstName?.message}
              />
            )}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <Controller
            name='lastName'
            control={control}
            rules={{ required: 'Last name is required' }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                size='small'
                label='Last Name *'
                error={!!errors.lastName}
                helperText={errors.lastName?.message}
              />
            )}
          />
        </Grid>
        
        {/* Email, Country Code, Phone Number in one row */}
        <Grid item xs={12} sm={4}>
          <Controller
            name='emailId'
            control={control}
            rules={{
              pattern: {
                value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                message: 'Invalid email address'
              }
            }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                size='small'
                label='Email'
                error={!!errors.emailId}
                helperText={errors.emailId?.message}
              />
            )}
          />
        </Grid>
        
        <Grid item xs={12} sm={4}>
          <Controller
            name='countryCode'
            control={control}
            rules={{ required: 'Country code is required' }}
            render={({ field }) => (
              <Autocomplete
                options={countries}
                autoHighlight
                getOptionLabel={opt => `${opt.code}  +${opt.phone}`}
                value={getSelectedCountry()}
                onChange={(_, newValue) => {
                  if (newValue) {
                    field.onChange(`+${newValue.phone}`)
                    setValue('dialCountryCode', newValue.code)
                  }
                }}
                renderOption={(props, option) => (
                  <Box component='li' sx={{ display: 'flex', alignItems: 'center', gap: 1 }} {...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=''
                    />
                    <span>{option.label}</span>
                    <Typography variant='caption' color='text.secondary' sx={{ ml: 'auto' }}>
                      +{option.phone}
                    </Typography>
                  </Box>
                )}
                renderInput={params => (
                  <TextField
                    {...params}
                    size='small'
                    label='Country Code *'
                    error={!!errors.countryCode}
                    helperText={errors.countryCode?.message}
                    inputProps={{ ...params.inputProps, autoComplete: 'new-password' }}
                  />
                )}
              />
            )}
          />
        </Grid>

        <Grid item xs={12} sm={4}>
          <Controller
            name='phoneNumber'
            control={control}
            rules={{
              required: 'Phone number is required',
              minLength: { value: 6, message: 'Enter a valid phone number' },
              pattern: { value: /^[0-9]+$/, message: 'Numbers only' },
            }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                size='small'
                label='Phone Number *'
                placeholder='9876543210'
                error={!!errors.phoneNumber}
                helperText={errors.phoneNumber?.message}
                inputProps={{ inputMode: 'numeric' }}
              />
            )}
          />
        </Grid>

        <Grid item xs={12}>
          <Controller
            name='address'
            control={control}
            rules={{ required: 'Address is required' }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                size='small'
                label='Address *'
                error={!!errors.address}
                helperText={errors.address?.message}
              />
            )}
          />
        </Grid>
        <Grid item xs={12} sm={4}>
          <Controller
            name='city'
            control={control}
            rules={{ required: 'City is required' }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                size='small'
                label='City *'
                error={!!errors.city}
                helperText={errors.city?.message}
              />
            )}
          />
        </Grid>
        <Grid item xs={12} sm={4}>
          <Controller
            name='state'
            control={control}
            rules={{ required: 'State is required' }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                size='small'
                label='State *'
                error={!!errors.state}
                helperText={errors.state?.message}
              />
            )}
          />
        </Grid>
        <Grid item xs={12} sm={4}>
          <Controller
            name='pinCode'
            control={control}
            rules={{
              required: 'Zip code is required',
              minLength: { value: 5, message: 'Zip code must be exactly 5 characters long' },
              maxLength: { value: 5, message: 'Zip code must be exactly 5 characters long' },
              pattern: { value: /^[0-9]+$/, message: 'Zip code must contain only numbers' },
            }}
            render={({ field }) => (
              <TextField
                {...field}
                fullWidth
                size='small'
                label='Zip Code *'
                placeholder='40001'
                error={!!errors.pinCode}
                helperText={errors.pinCode?.message}
                inputProps={{ 
                  inputMode: 'numeric',
                  maxLength: 5,
                  onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
                    // Prevent non-numeric characters
                    if (!/[0-9]/.test(e.key) && 
                        e.key !== 'Backspace' && 
                        e.key !== 'Delete' && 
                        e.key !== 'Tab' && 
                        e.key !== 'ArrowLeft' && 
                        e.key !== 'ArrowRight' && 
                        e.key !== 'ArrowUp' && 
                        e.key !== 'ArrowDown' &&
                        e.key !== 'Home' &&
                        e.key !== 'End') {
                      e.preventDefault()
                    }
                  }
                }}
              />
            )}
          />
        </Grid>
        <Grid item xs={12}>
          <Controller
            name='country'
            control={control}
            rules={{ required: 'Country is required' }}
            render={({ field }) => (
              <Autocomplete
                options={countries}
                autoHighlight
                getOptionLabel={opt => opt.label}
                value={getSelectedCountryField()}
                onChange={(_, newValue) => {
                  if (newValue) {
                    field.onChange(newValue.label)
                  }
                }}
                renderOption={(props, option) => (
                  <Box component='li' sx={{ display: 'flex', alignItems: 'center', gap: 1 }} {...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=''
                    />
                    <span>{option.label}</span>
                    <Typography variant='caption' color='text.secondary' sx={{ ml: 'auto' }}>
                      +{option.phone}
                    </Typography>
                  </Box>
                )}
                renderInput={params => (
                  <TextField
                    {...params}
                    size='small'
                    label='Country *'
                    error={!!errors.country}
                    helperText={errors.country?.message}
                    inputProps={{ ...params.inputProps, autoComplete: 'new-password' }}
                  />
                )}
              />
            )}
          />
        </Grid>
        <Grid item xs={12} sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 2 }}>
          <Button variant='outlined' color='secondary' onClick={onClose}>
            Cancel
          </Button>
          <Button type='submit' variant='contained'>
            Add Customer
          </Button>
        </Grid>
      </Grid>
    </form>
  )
}

export default CustomerForm