import React, { useState } from 'react';
import {
  Box,
  Typography,
  Button,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  TextField,
  CircularProgress,
  Alert,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Tooltip,
  Avatar
} from '@mui/material';
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Image as ImageIcon,
  ImageNotSupported as NoImageIcon
} from '@mui/icons-material';
import { useAdminCategories, useCreateCategory, useUpdateCategory, useDeleteCategory } from '../../hooks/categoryAdminHooks';
import ImageUploader from '../../components/ImageUploader';
import { useAuth } from '../../hooks/reduxHooks';
import imageUtils from '../../utils/imageUtils';

const AdminCategoriesPage = () => {
  const { apiKey } = useAuth();
  const [categoryToEdit, setCategoryToEdit] = useState(null);
  const [categoryToDelete, setCategoryToDelete] = useState(null);
  const [newCategory, setNewCategory] = useState({ name: '', description: '', imagePath: '' });
  const [categoryImages, setCategoryImages] = useState([]);
  const [openDialog, setOpenDialog] = useState(false);
  const [openDeleteDialog, setOpenDeleteDialog] = useState(false);
  const [showImageUpload, setShowImageUpload] = useState(false);
  
  // React Query hooks
  const { 
    data: categories, 
    isLoading, 
    error 
  } = useAdminCategories();
  
  const createCategory = useCreateCategory();
  const updateCategory = useUpdateCategory();
  const deleteCategory = useDeleteCategory();
  
  // Handle new category dialog
  const handleOpenNewDialog = () => {
    setCategoryToEdit(null);
    setNewCategory({ name: '', description: '', imagePath: '' });
    setCategoryImages([]);
    setShowImageUpload(false);
    setOpenDialog(true);
  };
  
  // Handle edit category dialog
  const handleOpenEditDialog = (category) => {
    setCategoryToEdit(category);
    setNewCategory({ 
      name: category.name, 
      description: category.description || '',
      imagePath: category.image_path || ''
    });
    
    // Set up category images for the uploader
    const images = [];
    if (category.image_path) {
      images.push({
        path: category.image_path,
        isPrimary: true,
        displayOrder: 0
      });
    }
    setCategoryImages(images);
    setShowImageUpload(false);
    setOpenDialog(true);
  };
  
  // Handle images change
  const handleImagesChange = (newImages) => {
    setCategoryImages(newImages);
    // Update the imagePath in the form data
    if (newImages.length > 0) {
      setNewCategory(prev => ({
        ...prev,
        imagePath: newImages[0].path
      }));
    } else {
      setNewCategory(prev => ({
        ...prev,
        imagePath: ''
      }));
    }
  };
  
  // Handle close dialog
  const handleCloseDialog = () => {
    setOpenDialog(false);
    setCategoryToEdit(null);
    setNewCategory({ name: '', description: '', imagePath: '' });
    setCategoryImages([]);
    setShowImageUpload(false);
  };
  
  // Handle save category (create or update)
  const handleSaveCategory = async () => {
    try {
      if (categoryToEdit) {
        // Update existing category
        await updateCategory.mutateAsync({ 
          id: categoryToEdit.id, 
          categoryData: newCategory 
        });
      } else {
        // Create new category
        await createCategory.mutateAsync(newCategory);
      }
      handleCloseDialog();
    } catch (error) {
      // Error is handled by the mutation
      console.error('Error saving category:', error);
    }
  };
  
  // Handle delete click
  const handleDeleteClick = (category) => {
    setCategoryToDelete(category);
    setOpenDeleteDialog(true);
  };
  
  // Confirm delete
  const handleConfirmDelete = async () => {
    if (categoryToDelete) {
      try {
        await deleteCategory.mutateAsync(categoryToDelete.id);
        setOpenDeleteDialog(false);
        setCategoryToDelete(null);
      } catch (error) {
        // Error is handled by the mutation
        console.error('Error deleting category:', error);
      }
    }
  };
  
  // Cancel delete
  const handleCancelDelete = () => {
    setOpenDeleteDialog(false);
    setCategoryToDelete(null);
  };
  
  // Handle form changes
  const handleChange = (e) => {
    const { name, value } = e.target;
    setNewCategory(prev => ({ ...prev, [name]: value }));
  };
  
  // Loading state
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }
  
  // Error state
  if (error) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading categories: {error.message}
      </Alert>
    );
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4" component="h1">
          Categories
        </Typography>

        <Button
          variant="contained"
          color="primary"
          startIcon={<AddIcon />}
          onClick={handleOpenNewDialog}
        >
          Add Category
        </Button>
      </Box>

      {/* Categories Table */}
      <TableContainer component={Paper}>
        <Table sx={{ minWidth: 650 }} aria-label="categories table">
          <TableHead>
            <TableRow>
              <TableCell>Image</TableCell>
              <TableCell>Name</TableCell>
              <TableCell>Description</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {categories && categories.length > 0 ? (
              categories.map((category) => (
                <TableRow key={category.id}>
                  <TableCell sx={{ width: 80 }}>
                    {category.image_path ? (
                      <Avatar
                        src={imageUtils.getImageUrl(category.image_path)}
                        alt={category.name}
                        variant="rounded"
                        sx={{ width: 60, height: 60 }}
                      />
                    ) : (
                      <Avatar
                        variant="rounded"
                        sx={{ width: 60, height: 60, bgcolor: 'grey.300' }}
                      >
                        <NoImageIcon color="action" />
                      </Avatar>
                    )}
                  </TableCell>
                  <TableCell>
                    <Typography variant="body1" fontWeight="medium">
                      {category.name}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" color="text.secondary">
                      {category.description || 'No description'}
                    </Typography>
                  </TableCell>
                  <TableCell align="right">
                    <Tooltip title="Edit">
                      <IconButton
                        color="primary"
                        onClick={() => handleOpenEditDialog(category)}
                        aria-label="edit"
                      >
                        <EditIcon />
                      </IconButton>
                    </Tooltip>
                    <Tooltip title="Delete">
                      <IconButton
                        color="error"
                        onClick={() => handleDeleteClick(category)}
                        aria-label="delete"
                      >
                        <DeleteIcon />
                      </IconButton>
                    </Tooltip>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={4} align="center">
                  <Typography variant="body1" py={3}>
                    No categories found. Add a category to get started.
                  </Typography>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Add/Edit Category Dialog */}
      <Dialog 
        open={openDialog} 
        onClose={handleCloseDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          {categoryToEdit ? 'Edit Category' : 'Add New Category'}
        </DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 1, mb: 2 }}>
            {/* Image preview or placeholder */}
            {showImageUpload ? (
              <Box sx={{ mb: 2 }}>
                <Typography variant="subtitle1" gutterBottom>
                  Category Image
                </Typography>
                <ImageUploader
                  images={categoryImages}
                  onChange={handleImagesChange}
                  multiple={false}
                  admin={true}
                />
                <Button 
                  size="small"
                  sx={{ mt: 1 }}
                  onClick={() => setShowImageUpload(false)}
                >
                  Hide Image Upload
                </Button>
              </Box>
            ) : (
              <Box 
                sx={{ 
                  display: 'flex', 
                  alignItems: 'center', 
                  mb: 2 
                }}
              >
                {categoryImages.length > 0 ? (
                  <Avatar
                    src={imageUtils.getImageUrl(categoryImages[0].path)}
                    alt="Category image"
                    variant="rounded"
                    sx={{ width: 80, height: 80, mr: 2 }}
                  />
                ) : (
                  <Avatar
                    variant="rounded"
                    sx={{ width: 80, height: 80, mr: 2, bgcolor: 'grey.200' }}
                  >
                    <NoImageIcon color="action" fontSize="large" />
                  </Avatar>
                )}
                <Button
                  variant="outlined"
                  startIcon={<ImageIcon />}
                  onClick={() => setShowImageUpload(true)}
                >
                  {categoryImages.length > 0 ? 'Change Image' : 'Add Image'}
                </Button>
                {categoryImages.length > 0 && (
                  <Button
                    variant="text"
                    color="error"
                    sx={{ ml: 1 }}
                    onClick={() => handleImagesChange([])}
                  >
                    Remove
                  </Button>
                )}
              </Box>
            )}
          </Box>

          <TextField
            autoFocus
            margin="dense"
            name="name"
            label="Category Name"
            type="text"
            fullWidth
            variant="outlined"
            value={newCategory.name}
            onChange={handleChange}
            required
            sx={{ mb: 2 }}
          />
          <TextField
            margin="dense"
            name="description"
            label="Description"
            type="text"
            fullWidth
            variant="outlined"
            value={newCategory.description}
            onChange={handleChange}
            multiline
            rows={3}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>Cancel</Button>
          <Button 
            onClick={handleSaveCategory} 
            variant="contained" 
            color="primary"
            disabled={!newCategory.name || 
              createCategory.isLoading || 
              updateCategory.isLoading}
          >
            {(createCategory.isLoading || updateCategory.isLoading) ? (
              <CircularProgress size={24} />
            ) : categoryToEdit ? 'Update' : 'Create'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={openDeleteDialog}
        onClose={handleCancelDelete}
      >
        <DialogTitle>Confirm Deletion</DialogTitle>
        <DialogContent>
          <DialogContentText>
            Are you sure you want to delete the category "{categoryToDelete?.name}"? 
            {categoryToDelete && <strong> This action cannot be undone.</strong>}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelDelete} color="primary">
            Cancel
          </Button>
          <Button 
            onClick={handleConfirmDelete} 
            color="error" 
            variant="contained"
            disabled={deleteCategory.isLoading}
          >
            {deleteCategory.isLoading ? <CircularProgress size={24} /> : 'Delete'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AdminCategoriesPage;