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

// ** MUI
import {
  Box,
  Grid,
  Dialog,
  Button,
  TextField,
  IconButton,
  Typography,
  Fade,
  FadeProps,
  DialogContent,
  DialogActions,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Skeleton,
  Divider,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Switch,
  FormControlLabel
} from '@mui/material'

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

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

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

interface Attribute {
  attributeName: string
  isRequired: boolean
}

export interface CategoryFormValues {
  name: string
  description?: string
  parentUid?: { uid: string } | null
  attributeKeys: Attribute[]
}

interface ParentCategory {
  uid: string
  name: string
}

interface CreateCategoryProps {
  show: boolean
  mode: 'create' | 'edit'
  onClose: () => void
  onSubmit: (data: CategoryFormValues) => void
  initialData?: CategoryFormValues | null
  isSubmitting?: boolean
  isLoadingData?: boolean
  parentCategories?: ParentCategory[] // Made optional
}

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

const DEFAULT_VALUES: CategoryFormValues = {
  name: '',
  description: '',
  parentUid: null,
  attributeKeys: [],
}

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

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

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

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

const CreateCategory = ({
  show,
  mode,
  onClose,
  onSubmit,
  initialData = null,
  isSubmitting = false,
  isLoadingData = false,
  parentCategories = [], // Default to empty array
}: CreateCategoryProps) => {
  const isEdit = mode === 'edit'

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

  const { fields, append, remove } = useFieldArray({
    control,
    name: 'attributeKeys'
  })

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

  const addVariation = () => {
    append({ attributeName: '', isRequired: false })
  }

  // Get the current parent category name for display in edit mode
  const getCurrentParentName = () => {
    if (!isEdit || !initialData?.parentUid?.uid) return ''

    // Ensure parentCategories is an array before using find
    if (!Array.isArray(parentCategories)) return ''
    const parent = parentCategories.find(p => p.uid === initialData.parentUid?.uid)
    return parent?.name || ''
  }

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

  return (
    <Dialog
      fullWidth
      open={show}
      maxWidth='md'
      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:category'}
              style={{ fontSize: 24, color: isEdit ? '#FF9F43' : '#7367F0' }}
            />
          </Box>
          <Typography variant='h5' fontWeight={600} mb={0.5}>
            {isEdit ? 'Edit Category' : 'Add Category'}
          </Typography>
          <Typography variant='body2' color='text.secondary'>
            {isEdit ? 'Update category information below' : 'Fill in the details to add a new category'}
          </Typography>
        </Box>

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

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

              {/* Parent Category */}
              <Grid item xs={12}>
                {isEdit ? (

                  // In edit mode, show as disabled text field
                  <TextField
                    fullWidth
                    label='Parent Category'
                    value={getCurrentParentName() || 'None'}
                    disabled
                    InputProps={{
                      readOnly: true,
                    }}
                  />
                ) : (

                  // In create mode, show as select dropdown
                  <FormControl fullWidth>
                    <InputLabel id='parent-category-label'>Parent Category</InputLabel>
                    <Controller
                      name='parentUid'
                      control={control}
                      render={({ field }) => (
                        <Select
                          {...field}
                          labelId='parent-category-label'
                          label='Parent Category'
                          disabled={isSubmitting}
                          value={field.value?.uid || ''}
                          onChange={(e) => {
                            const selected = Array.isArray(parentCategories) 
                              ? parentCategories.find(p => p.uid === e.target.value)
                              : null
                            field.onChange(selected ? { uid: selected.uid } : null)
                          }}
                        >
                          <MenuItem value=''>None</MenuItem>
                          {Array.isArray(parentCategories) && parentCategories.map((category) => (
                            <MenuItem key={category.uid} value={category.uid}>
                              {category.name}
                            </MenuItem>
                          ))}
                        </Select>
                      )}
                    />
                  </FormControl>
                )}
              </Grid>

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

              {/* Description */}
              <Grid item xs={12}>
                <Controller
                  name='description'
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      multiline
                      rows={3}
                      label='Description (optional)'
                      placeholder='Enter description about the category...'
                      error={!!errors.description}
                      helperText={errors.description?.message}
                      disabled={isSubmitting}
                    />
                  )}
                />
              </Grid>

              {/* Variations Section */}
              <Grid item xs={12}>
                <Box sx={{ mt: 2 }}>
                  <Typography variant='subtitle1' fontWeight={600} sx={{ mb: 2 }}>
                    Variations
                  </Typography>
                  
                  <TableContainer component={Paper} variant='outlined'>
                    <Table>
                      <TableHead>
                        <TableRow>
                          <TableCell><Typography fontWeight={600}>Variation Name</Typography></TableCell>
                          <TableCell align='center'><Typography fontWeight={600}>Required</Typography></TableCell>
                          <TableCell align='center'><Typography fontWeight={600}>Action</Typography></TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {fields.length === 0 ? (
                          <TableRow>
                            <TableCell colSpan={3} align='center' sx={{ py: 3 }}>
                              <Typography variant='body2' color='text.secondary'>
                                No variations added. Click "Add New" to add variations.
                              </Typography>
                            </TableCell>
                          </TableRow>
                        ) : (
                          fields.map((field, index) => (
                            <TableRow key={field.id}>
                              <TableCell>
                                <Controller
                                  name={`attributeKeys.${index}.attributeName`}
                                  control={control}
                                  rules={{
                                    required: 'Variation name is required',
                                    minLength: { value: 2, message: 'Minimum 2 characters' },
                                  }}
                                  render={({ field: fieldProps, fieldState: { error } }) => (
                                    <TextField
                                      {...fieldProps}
                                      fullWidth
                                      size='small'
                                      placeholder='e.g. Color, Size'
                                      error={!!error}
                                      helperText={error?.message}
                                      disabled={isSubmitting}
                                    />
                                  )}
                                />
                              </TableCell>
                              <TableCell align='center'>
                                <Controller
                                  name={`attributeKeys.${index}.isRequired`}
                                  control={control}
                                  render={({ field: fieldProps }) => (
                                    <FormControlLabel
                                      control={
                                        <Switch
                                          {...fieldProps}
                                          checked={fieldProps.value}
                                          onChange={(e) => fieldProps.onChange(e.target.checked)}
                                          disabled={isSubmitting}
                                          color='primary'
                                        />
                                      }
                                      label={fieldProps.value ? 'Yes' : 'No'}
                                      sx={{ m: 0 }}
                                    />
                                  )}
                                />
                              </TableCell>
                              <TableCell align='center'>
                                <IconButton
                                  size='small'
                                  color='error'
                                  onClick={() => remove(index)}
                                  disabled={isSubmitting || fields.length === 1}
                                >
                                  <Icon icon='tabler:trash' fontSize={18} />
                                </IconButton>
                              </TableCell>
                            </TableRow>
                          ))
                        )}
                      </TableBody>
                    </Table>
                  </TableContainer>

                  <Button
                    variant='outlined'
                    startIcon={<Icon icon='tabler:plus' />}
                    onClick={addVariation}
                    disabled={isSubmitting}
                    sx={{ mt: 2 }}
                  >
                    Add New
                  </Button>
                </Box>
              </Grid>

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

      {/* Footer actions */}
      <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='category-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' : 'Submit'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

export default CreateCategory