import { Ref, forwardRef, ReactElement, useEffect } from 'react'

// ** MUI
import {
  Box,
  Grid,
  Dialog,
  Button,
  TextField,
  IconButton,
  Typography,
  Fade,
  FadeProps,
  DialogContent,
  DialogActions,
  Autocomplete,
  CircularProgress,
  Skeleton,
  Divider,
} from '@mui/material'

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

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

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

// ============================================================
//  Types
// ============================================================

export interface CustomerFormValues {
  firstName: string
  lastName: string
  phoneNumber: string
  phoneCode: string        // ISO  e.g. "US"
  dialCountryCode: string  // dial e.g. "+1"
  emailId: string
  address: string
  city: string
  state: string
  country: string
  pinCode: string
}

interface CreateCustomerProps {
  show: boolean
  mode: 'create' | 'edit'
  onClose: () => void
  onSubmit: (data: CustomerFormValues) => void
  initialData?: CustomerFormValues | null
  isSubmitting?: boolean
  isLoadingData?: boolean
}

// ============================================================
//  Constants
// ============================================================

const DEFAULT_VALUES: CustomerFormValues = {
  firstName:       '',
  lastName:        '',
  phoneNumber:     '',
  phoneCode:       'US',
  dialCountryCode: '+1',
  emailId:         '',
  address:         '',
  city:            '',
  state:           '',
  country:         '',
  pinCode:         '',
}

// ============================================================
//  Transition
// ============================================================

const Transition = forwardRef(function Transition(
  props: FadeProps & { children?: ReactElement<any, any> },
  ref: Ref<unknown>
) {
  return <Fade ref={ref} {...props} />
})

// ============================================================
//  Form skeleton while GET /customer/:uid loads
// ============================================================

const FormSkeleton = () => (
  <Grid container spacing={4}>
    <Grid item xs={12} sm={6}><Skeleton variant='rounded' height={56} /></Grid>
    <Grid item xs={12} sm={6}><Skeleton variant='rounded' height={56} /></Grid>
    <Grid item xs={12}><Skeleton variant='rounded' height={56} /></Grid>
    <Grid item xs={12}><Skeleton variant='rounded' height={80} /></Grid>
    <Grid item xs={12} sm={6}><Skeleton variant='rounded' height={56} /></Grid>
    <Grid item xs={12} sm={6}><Skeleton variant='rounded' height={56} /></Grid>
    <Grid item xs={12} sm={6}><Skeleton variant='rounded' height={56} /></Grid>
    <Grid item xs={12} sm={6}><Skeleton variant='rounded' height={56} /></Grid>
  </Grid>
)

// ============================================================
//  Component
// ============================================================

const CreateCustomer = ({
  show,
  mode,
  onClose,
  onSubmit,
  initialData = null,
  isSubmitting = false,
  isLoadingData = false,
}: CreateCustomerProps) => {
  const isEdit = mode === 'edit'

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm<CustomerFormValues>({ defaultValues: DEFAULT_VALUES })

  const selectedPhoneCode = watch('phoneCode')

  // Populate or reset form when modal opens or initialData arrives
  useEffect(() => {
    if (!show) return
    if (isEdit && initialData) {
      reset(initialData)
    } else if (!isEdit) {
      reset(DEFAULT_VALUES)
    }
  }, [show, isEdit, initialData, reset])

  const getSelectedCountry = () =>
    countries.find(c => c.code === selectedPhoneCode) ?? null

  const handleClose = () => {
    if (isSubmitting) return
    onClose()
  }

  // ── Render ─────────────────────────────────────────────────

  return (
    <Dialog
      fullWidth
      open={show}
      maxWidth='sm'
      scroll='body'
      onClose={handleClose}
      TransitionComponent={Transition}
      PaperProps={{ sx: { borderRadius: 3 } }}
    >
      <DialogContent
        sx={{
          position: 'relative',
          px: { xs: 5, sm: 8 },
          pt: { xs: 6, sm: 7 },
          pb: 2,
        }}
      >
        {/* Close */}
        <IconButton
          size='small'
          onClick={handleClose}
          disabled={isSubmitting}
          aria-label='Close'
          sx={{ position: 'absolute', right: 12, top: 12, color: 'text.secondary' }}
        >
          <Icon icon='tabler:x' />
        </IconButton>

        {/* Header */}
        <Box sx={{ mb: 4, textAlign: 'center' }}>
          <Box
            sx={{
              width: 52,
              height: 52,
              borderRadius: '50%',
              bgcolor: isEdit ? 'warning.light' : 'primary.light',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              mx: 'auto',
              mb: 2,
            }}
          >
            <Icon
              icon={isEdit ? 'tabler:edit' : 'tabler:user-plus'}
              style={{ fontSize: 24, color: isEdit ? '#FF9F43' : '#7367F0' }}
            />
          </Box>
          <Typography variant='h5' fontWeight={600} mb={0.5}>
            {isEdit ? 'Edit Customer' : 'Add New Customer'}
          </Typography>
          <Typography variant='body2' color='text.secondary'>
            {isEdit ? 'Update customer information below' : 'Fill in the details to add a new customer'}
          </Typography>
        </Box>

        <Divider sx={{ mb: 4 }} />

        {/* Skeleton or form */}
        {isLoadingData ? (
          <FormSkeleton />
        ) : (
          <Box component='form' id='customer-form' onSubmit={handleSubmit(onSubmit)} noValidate>
            <Grid container spacing={4}>

              {/* First Name */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name='firstName'
                  control={control}
                  rules={{
                    required: 'First name is required',
                    minLength: { value: 2, message: 'Minimum 2 characters' },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='First Name *'
                      placeholder='e.g. John'
                      error={!!errors.firstName}
                      helperText={errors.firstName?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* Last Name */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name='lastName'
                  control={control}
                  rules={{
                    required: 'Last name is required',
                    minLength: { value: 2, message: 'Minimum 2 characters' },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='Last Name *'
                      placeholder='e.g. Doe'
                      error={!!errors.lastName}
                      helperText={errors.lastName?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* Phone Number with Country Code */}
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>
                  {/* Country autocomplete */}
                  <Controller
                    name='phoneCode'
                    control={control}
                    rules={{ required: 'Country is required' }}
                    render={({ field }) => (
                      <Autocomplete
                        sx={{ width: 210, flexShrink: 0 }}
                        options={countries}
                        autoHighlight
                        getOptionLabel={opt => `${opt.code}  +${opt.phone}`}
                        value={getSelectedCountry()}
                        onChange={(_, newValue) => {
                          if (newValue) {
                            field.onChange(newValue.code)
                            setValue('dialCountryCode', `+${newValue.phone}`)
                          }
                        }}
                        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}
                            label='Country Code *'
                            error={!!errors.phoneCode}
                            helperText={errors.phoneCode?.message}
                            disabled={isSubmitting}
                            inputProps={{ ...params.inputProps, autoComplete: 'new-password' }}
                          />
                        )}
                      />
                    )}
                  />

                  {/* Phone number */}
                  <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
                        label='Phone Number *'
                        placeholder='9876543210'
                        error={!!errors.phoneNumber}
                        helperText={errors.phoneNumber?.message}
                        disabled={isSubmitting}
                        inputProps={{ inputMode: 'numeric' }}
                      />
                    )}
                  />
                </Box>
              </Grid>

              {/* Email */}
              <Grid item xs={12}>
                <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
                      type='email'
                      label='Email'
                      placeholder='john@company.com'
                      error={!!errors.emailId}
                      helperText={errors.emailId?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* Address */}
              <Grid item xs={12}>
                <Controller
                  name='address'
                  control={control}
                  rules={{
                    required: 'Address is required',
                    minLength: { value: 5, message: 'Please enter a valid address' },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      multiline
                      rows={2}
                      label='Address *'
                      placeholder='123 Main Street, Near Central Park'
                      error={!!errors.address}
                      helperText={errors.address?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* City */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name='city'
                  control={control}
                  rules={{
                    required: 'City is required',
                    minLength: { value: 2, message: 'Minimum 2 characters' },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='City *'
                      placeholder='e.g. Mumbai'
                      error={!!errors.city}
                      helperText={errors.city?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* State */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name='state'
                  control={control}
                  rules={{
                    required: 'State is required',
                    minLength: { value: 2, message: 'Minimum 2 characters' },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='State *'
                      placeholder='e.g. Maharashtra'
                      error={!!errors.state}
                      helperText={errors.state?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* Country */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name='country'
                  control={control}
                  rules={{
                    required: 'Country is required',
                    minLength: { value: 2, message: 'Minimum 2 characters' },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='Country *'
                      placeholder='e.g. India'
                      error={!!errors.country}
                      helperText={errors.country?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* Zip Code */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name='pinCode'
                  control={control}
                  rules={{
                    required: 'Zip code is required',
                    minLength: { value: 4, message: 'Enter a valid zip code' },
                    maxLength: { value: 10, message: 'Zip code cannot exceed 10 characters' },
                    pattern: { value: /^[0-9]+$/, message: 'Numbers only' },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='Zip Code *'
                      placeholder='40001'
                      error={!!errors.pinCode}
                      helperText={errors.pinCode?.message}
                      disabled={isSubmitting}
                      inputProps={{ inputMode: 'numeric' }}
                    />
                  )}
                />
              </Grid>

            </Grid>
          </Box>
        )}
      </DialogContent>

      {/* Footer actions — outside the form, linked via form='customer-form' */}
      <DialogActions sx={{ px: { xs: 5, sm: 8 }, pb: { xs: 5, sm: 6 }, pt: 3, gap: 2, justifyContent: 'flex-end' }}>
        <Button
          variant='outlined'
          color='secondary'
          onClick={handleClose}
          disabled={isSubmitting || isLoadingData}
        >
          Cancel
        </Button>
        <Button
          type='submit'
          form='customer-form'
          variant='contained'
          disabled={isSubmitting || isLoadingData}
          startIcon={
            isSubmitting
              ? <CircularProgress size={16} color='inherit' />
              : <Icon icon={isEdit ? 'tabler:device-floppy' : 'tabler:plus'} />
          }
        >
          {isSubmitting
            ? isEdit ? 'Saving…' : 'Creating…'
            : isEdit ? 'Save Changes' : 'Create Customer'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

export default CreateCustomer