'use client'
import React, { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Box, Button, Card, CardContent, CircularProgress, Grid, TextField, Typography } from '@mui/material'
import useAPI from '@/hooks/useAPI'

const AddCategoryPage = () => {
  const [name, setName] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const router = useRouter()
  const api = useAPI()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!name.trim()) {
      setError('Category name is required')
      return
    }

    setLoading(true)
    setError('')

    try {
      const apiInstance = await api
      await apiInstance.category.create({ name, deviceId: "admin_123"})

      console.log('Category created successfully', name)
      // Redirect to category list page after successful creation
      router.push('/admin/category')
    } catch (error: any) {
      console.error('Error creating category:', error)
      setError(error.response?.data?.message || 'Failed to create category')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Box sx={{ p: 4 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 4 }}>
        <Typography variant='h4'>Add New Category</Typography>
        <Button variant='outlined' onClick={() => router.push('/admin/category')}>
          Back to Categories
        </Button>
      </Box>

      <Card>
        <CardContent>
          <form onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label='Category Name'
                  value={name}
                  onChange={e => setName(e.target.value)}
                  error={!!error}
                  helperText={error}
                  required
                />
              </Grid>

              <Grid item xs={12}>
                <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Button
                    type='button'
                    variant='outlined'
                    sx={{ mr: 2 }}
                    onClick={() => router.push('/admin/category')}
                  >
                    Cancel
                  </Button>
                  <Button
                    type='submit'
                    variant='contained'
                    disabled={loading}
                    startIcon={loading ? <CircularProgress size={20} /> : null}
                  >
                    {loading ? 'Creating...' : 'Create Category'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  )
}

export default AddCategoryPage
