// src/views/components/product/drawers/AddCategoryDrawer.tsx

import React, { useState } from 'react'
import {
  Box,
  Button,
  Typography,
  Drawer,
  IconButton,
  Divider,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Switch,
  FormControlLabel,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  CircularProgress,
} from '@mui/material'
import Icon from 'src/@core/components/icon'
import { useForm, Controller, useFieldArray } from 'react-hook-form'
import { Category, CategoryPayload } from '../types'
import { createCategory, getErrorMessage } from '../hooks'
import toast from 'react-hot-toast'

interface AddCategoryDrawerProps {
  open: boolean
  onClose: () => void
  onSuccess: () => void
  parentCategories: Category[]
}

const AddCategoryDrawer = ({ open, onClose, onSuccess, parentCategories = [] }: AddCategoryDrawerProps) => {
  const [loading, setLoading] = useState(false)

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<CategoryPayload>({
    defaultValues: {
      name: '',
      description: '',
      parentUid: null,
      attributeKeys: [],
    }
  })

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

  const onSubmit = async (data: CategoryPayload) => {
    setLoading(true)
    try {
      await createCategory(data)
      toast.success('Category created successfully')
      onSuccess()
      onClose()
      reset({
        name: '',
        description: '',
        parentUid: null,
        attributeKeys: [],
      })
    } catch (error) {
      toast.error(getErrorMessage(error, 'Failed to create category'))
    } finally {
      setLoading(false)
    }
  }

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

  return (
    <Drawer anchor='right' open={open} onClose={onClose}>
      <Box sx={{ width: 500, p: 4, maxHeight: '100vh', overflow: 'auto' }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant='h6'>Add New Category</Typography>
          <IconButton onClick={onClose}>
            <Icon icon='tabler:x' />
          </IconButton>
        </Box>
        <Divider sx={{ mb: 3 }} />

        <Box component='form' onSubmit={handleSubmit(onSubmit)} noValidate>
          <FormControl fullWidth sx={{ mb: 3 }}>
            <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={loading}
                  value={field.value?.uid || ''}
                  onChange={(e) => {
                    const selected = parentCategories.find(p => p.uid === e.target.value)
                    field.onChange(selected ? { uid: selected.uid } : null)
                  }}
                >
                  <MenuItem value=''>None</MenuItem>
                  {parentCategories.map((category) => (
                    <MenuItem key={category.uid} value={category.uid}>
                      {category.name}
                    </MenuItem>
                  ))}
                </Select>
              )}
            />
          </FormControl>

          <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={loading}
                sx={{ mb: 3 }}
              />
            )}
          />

          <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={loading}
                sx={{ mb: 3 }}
              />
            )}
          />

          <Box sx={{ mt: 2, mb: 3 }}>
            <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={loading}
                              />
                            )}
                          />
                        </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={loading}
                                    color='primary'
                                  />
                                }
                                label={fieldProps.value ? 'Yes' : 'No'}
                                sx={{ m: 0 }}
                              />
                            )}
                          />
                        </TableCell>
                        <TableCell align='center'>
                          <IconButton
                            size='small'
                            color='error'
                            onClick={() => remove(index)}
                            disabled={loading || 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={loading}
              sx={{ mt: 2 }}
            >
              Add New
            </Button>
          </Box>

          <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 3 }}>
            <Button variant='outlined' onClick={onClose} disabled={loading}>
              Cancel
            </Button>
            <Button type='submit' variant='contained' disabled={loading}>
              {loading ? <CircularProgress size={24} /> : 'Create Category'}
            </Button>
          </Box>
        </Box>
      </Box>
    </Drawer>
  )
}

export default AddCategoryDrawer