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

const EditCategoryPage = () => {
  const [name, setName] = useState('')
  const [loading, setLoading] = useState(false)
  const [fetchLoading, setFetchLoading] = useState(true)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)
  const router = useRouter()
  const params = useParams()
  const categoryId = params.id as string
  const api = useAPI()

  useEffect(() => {
    const fetchCategory = async () => {
      try {
        setFetchLoading(true)
        const apiInstance = await api
        const response = await apiInstance.category.getById(categoryId)
        
        if (response.data && response.data.category) {
          setName(response.data.category.name)
        } else {
          setError('Category not found')
        }
      } catch (error) {
        console.error('Error fetching category:', error)
        setError('Failed to fetch category details')
      } finally {
        setFetchLoading(false)
      }
    }

    if (categoryId) {
      fetchCategory()
    }
  }, [categoryId])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!name.trim()) {
      setError('Category name is required')
      return
    }
    
    setLoading(true)
    setError('')
    setSuccess(false)
    
    try {
      const apiInstance = await api
      await apiInstance.category.update(categoryId, { name })
      
      setSuccess(true)
      // Optionally redirect after a delay
      setTimeout(() => {
        router.push('/admin/category')
      }, 1500)
    } catch (error: any) {
      console.error('Error updating category:', error)
      setError(error.response?.data?.message || 'Failed to update category')
    } finally {
      setLoading(false)
    }
  }

  if (fetchLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
        <CircularProgress />
      </Box>
    )
  }

  return (
    <Box sx={{ p: 4 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 4 }}>
        <Typography variant="h4">Edit Category</Typography>
        <Button variant="outlined" onClick={() => router.push('/admin/category')}>
          Back to Categories
        </Button>
      </Box>
      
      {/* {success && (
        <Alert severity="success" sx={{ mb: 3 }}>
          Category updated successfully!
        </Alert>
      )} */}
      
      <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 ? 'Updating...' : 'Update Category'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  )
}

export default EditCategoryPage
