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

// ** MUI
import {
  Box,
  Grid,
  Dialog,
  Button,
  TextField,
  IconButton,
  Typography,
  Fade,
  FadeProps,
  DialogContent,
  DialogActions,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio,
  Skeleton,
  Divider,
  FormHelperText,
  CircularProgress
} from '@mui/material'

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

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

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

export interface TaxFormValues {
  taxName: string
  taxType: string
  taxValue: number
}

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

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

const DEFAULT_VALUES: TaxFormValues = {
  taxName: '',
  taxType: 'flat',
  taxValue: 0,
}

const TAX_TYPES = ['flat', 'percentage'] as const

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

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

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

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

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

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

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

  const taxType = watch('taxType')

  // 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 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:percent'}
              style={{ fontSize: 24, color: isEdit ? '#FF9F43' : '#7367F0' }}
            />
          </Box>
          <Typography variant='h5' fontWeight={600} mb={0.5}>
            {isEdit ? 'Edit Product Tax' : 'Add Product Tax'}
          </Typography>
          <Typography variant='body2' color='text.secondary'>
            {isEdit ? 'Update tax information below' : 'Fill in the details to add a new tax'}
          </Typography>
        </Box>

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

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

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

              {/* Tax Type - Radio Buttons */}
              <Grid item xs={12}>
                <FormControl component="fieldset" error={!!errors.taxType}>
                  <FormLabel component="legend" sx={{ mb: 1, fontWeight: 500 }}>
                    Tax Type
                  </FormLabel>
                  <Controller
                    name='taxType'
                    control={control}
                    rules={{ required: 'Tax type is required' }}
                    render={({ field }) => (
                      <RadioGroup
                        {...field}
                        row
                        aria-label="tax-type"
                        name="tax-type-radio"
                      >
                        {TAX_TYPES.map((type) => (
                          <FormControlLabel
                            key={type}
                            value={type}
                            control={<Radio />}
                            label={type}
                            disabled={isSubmitting}
                          />
                        ))}
                      </RadioGroup>
                    )}
                  />
                  {errors.taxType && (
                    <FormHelperText>{errors.taxType.message}</FormHelperText>
                  )}
                </FormControl>
              </Grid>

              {/* Tax Value */}
              <Grid item xs={12}>
                <Controller
                  name='taxValue'
                  control={control}
                  rules={{
                    required: 'Tax value is required',
                    min: { value: 0, message: 'Value must be greater than or equal to 0' },
                    max: { 
                      value: taxType === 'percentage' ? 100 : 999999,
                      message: taxType === 'percentage' ? 'Percentage cannot exceed 100' : 'Value is too high' 
                    },
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      type='number'
                      label='Tax Value'
                      placeholder={taxType === 'percentage' ? 'e.g. 10' : 'e.g. 50.00'}
                      error={!!errors.taxValue}
                      helperText={errors.taxValue?.message || (taxType === 'Percentage' ? 'Enter value as percentage (0-100)' : 'Enter flat tax amount')}
                      disabled={isSubmitting}
                      InputProps={{
                        endAdornment: taxType === 'percentage' ? '%' : undefined,
                      }}
                      inputProps={{ 
                        step: taxType === 'percentage' ? 0.01 : 0.01,
                        min: 0
                      }}
                    />
                  )}
                />
              </Grid>

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

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

export default CreateTax