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 VendorFormValues {
  vendorName: string
  companyName: string
  address: string
  email: string
  phoneNumber: string
  phoneCode: string        // ISO  e.g. "US"
  dialCountryCode: string  // dial e.g. "+1"
  vendorType: string
}

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

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

const DEFAULT_VALUES: VendorFormValues = {
  vendorName:      '',
  companyName:     '',
  address:         '',
  email:           '',
  phoneNumber:     '',
  phoneCode:       'US',
  dialCountryCode: '+1',
  vendorType:      '',
}

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

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

// ============================================================
//  Form skeleton while GET /vendor/: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} 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={80} /></Grid>
    <Grid item xs={12}><Skeleton variant='rounded' height={56} /></Grid>
  </Grid>
)

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

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

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm<VendorFormValues>({ 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:building-store'}
              style={{ fontSize: 24, color: isEdit ? '#FF9F43' : '#7367F0' }}
            />
          </Box>
          <Typography variant='h5' fontWeight={600} mb={0.5}>
            {isEdit ? 'Edit Vendor' : 'Add New Vendor'}
          </Typography>
          <Typography variant='body2' color='text.secondary'>
            {isEdit ? 'Update vendor information below' : 'Fill in the details to add a new vendor'}
          </Typography>
        </Box>

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

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

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

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

              {/* Email */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name='email'
                  control={control}
                  rules={{
                    required: 'Email is required',
                    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 Address'
                      placeholder='john@company.com'
                      error={!!errors.email}
                      helperText={errors.email?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* Vendor Type - Changed to TextField */}
              <Grid item xs={12} sm={6}>
                <Controller
                  name='vendorType'
                  control={control}
                  rules={{
                    required: 'Vendor type is required',
                    minLength: { value: 2, message: 'Minimum 2 characters' },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      label='Vendor Type'
                      placeholder='e.g. Supplier, Distributor'
                      error={!!errors.vendorType}
                      helperText={errors.vendorType?.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, City, Country'
                      error={!!errors.address}
                      helperText={errors.address?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* Country + Phone */}
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, alignItems: 'flex-start' }}>

                  {/* Country autocomplete */}
                  <Controller
                    name='phoneCode'
                    control={control}
                    rules={{ required: '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'
                            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>

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

      {/* Footer actions — outside the form, linked via form='vendor-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='vendor-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 Vendor'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

export default CreateVendor