import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Paper,
  TextField,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  InputAdornment,
  FormHelperText,
  Grid,
  Divider,
  Chip,
  CircularProgress,
  Alert,
  Snackbar,
  Autocomplete,
  FormControlLabel,
  Checkbox,
  Card,
  CardContent,
} from '@mui/material';
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import SaveIcon from '@mui/icons-material/Save';
import NotificationsActiveIcon from '@mui/icons-material/NotificationsActive';
import ImageUploader from '@components/ImageUploader';
import apiClient from '@services/api';
import { useAuth } from '@hooks/reduxHooks';

const ProductEditPage = () => {
  const { pathname } = useLocation();
  const id = pathname.split('/').pop();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { apiKey, userData } = useAuth();
  const isNewProduct = id === 'new';
  
  // Form state
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    categoryName: '',
    price: '',
    stockQuantity: '',
    weightGrams: '',
    lengthCm: '',
    widthCm: '',
    heightCm: '',
    origin: '',
    age: '',
    materialType: '',
    color: '',
    tags: [],
    images: []
  });

  // Notification state
  const [notificationEnabled, setNotificationEnabled] = useState(false);
  const [notificationEmail, setNotificationEmail] = useState('');
  const [stockThreshold, setStockThreshold] = useState(1);

  // Validation state
  const [errors, setErrors] = useState({});
  
  // Notification state
  const [notification, setNotification] = useState({
    open: false,
    message: '',
    severity: 'success'
  });

  // Fetch categories
  const { data: categories, isLoading: categoriesLoading } = useQuery({
    queryKey: ['categories'],
    queryFn: async () => {
      const response = await apiClient.get('/products/categories/all');
      return response.data;
    }
  });

  // Fetch all available tags
  const { data: allTags, isLoading: tagsLoading } = useQuery({
    queryKey: ['tags'],
    queryFn: async () => {
      const response = await apiClient.get('/products/tags/all');
      return response.data;
    }
  });

  // Fetch product data if editing
  const {
    data: product,
    isLoading: productLoading,
    error: productError
  } = useQuery({
    queryKey: ['product', id],
    queryFn: async () => {
      const response = await apiClient.get(`/products/${id}`);
      return response.data[0];
    },
    enabled: !isNewProduct 
  });

  // Create product mutation
  const createProduct = useMutation({
    mutationFn: async (productData) => {
      return await apiClient.post('/admin/products', productData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-products'] });
      setNotification({
        open: true,
        message: 'Product created successfully!',
        severity: 'success'
      });
      // Redirect after a short delay
      setTimeout(() => {
        navigate('/admin/products');
      }, 1500);
    },
    onError: (error) => {
      setNotification({
        open: true,
        message: `Failed to create product: ${error.message}`,
        severity: 'error'
      });
    }
  });

  // Update product mutation
  const updateProduct = useMutation({
    mutationFn: async ({ id, productData }) => {
      return await apiClient.put(`/admin/products/${id}`, productData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-products'] });
      queryClient.invalidateQueries({ queryKey: ['product', id] });
      setNotification({
        open: true,
        message: 'Product updated successfully!',
        severity: 'success'
      });
    },
    onError: (error) => {
      setNotification({
        open: true,
        message: `Failed to update product: ${error.message}`,
        severity: 'error'
      });
    }
  });

  // Save stock notification settings
  const saveStockNotification = useMutation({
    mutationFn: async (notificationData) => {
      return await apiClient.post(`/admin/products/${id}/stock-notification`, notificationData);
    },
    onSuccess: () => {
      setNotification({
        open: true,
        message: 'Stock notification settings saved!',
        severity: 'success'
      });
    },
    onError: (error) => {
      setNotification({
        open: true,
        message: `Failed to save notification settings: ${error.message}`,
        severity: 'error'
      });
    }
  });

  // Handle form changes
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear validation error when field is edited
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
  };
  
  // Handle tags change
  const handleTagsChange = (event, newTags) => {
    setFormData(prev => ({ ...prev, tags: newTags }));
  };
  
  const deduplicateImages = (images) => {
    const uniquePaths = new Set();
    return images.filter(img => {
      const path = img.path || img;
      if (uniquePaths.has(path)) {
        return false;
      }
      uniquePaths.add(path);
      return true;
    });
  };

  // Handle images change
  
  const handleImagesChange = (newImages) => {
    const uniqueImages = deduplicateImages(newImages);
    setFormData(prev => ({ ...prev, images: uniqueImages }));
  };

  // Handle notification checkbox change
  const handleNotificationToggle = (event) => {
    setNotificationEnabled(event.target.checked);
  };

  // Handle notification email change
  const handleNotificationEmailChange = (e) => {
    setNotificationEmail(e.target.value);
  };

  // Handle stock threshold change
  const handleStockThresholdChange = (e) => {
    let value = parseInt(e.target.value);
    if (isNaN(value) || value < 1) {
      value = 1;
    } else if (value > parseInt(formData.stockQuantity)) {
      value = parseInt(formData.stockQuantity);
    }
    setStockThreshold(value);
  };
  
  // Validate form
  const validateForm = () => {
    const newErrors = {};
    
    // Required fields
    if (!formData.name) newErrors.name = 'Name is required';
    if (!formData.description) newErrors.description = 'Description is required';
    if (!formData.categoryName) newErrors.categoryName = 'Category is required';
    
    // Price validation
    if (!formData.price) {
      newErrors.price = 'Price is required';
    } else if (isNaN(formData.price) || parseFloat(formData.price) <= 0) {
      newErrors.price = 'Price must be a positive number';
    }
    
    // Stock validation
    if (!formData.stockQuantity) {
      newErrors.stockQuantity = 'Stock quantity is required';
    } else if (isNaN(formData.stockQuantity) || parseInt(formData.stockQuantity) < 0) {
      newErrors.stockQuantity = 'Stock quantity must be a non-negative number';
    }
    
    // Numeric field validations
    if (formData.weightGrams && (isNaN(formData.weightGrams) || parseFloat(formData.weightGrams) <= 0)) {
      newErrors.weightGrams = 'Weight must be a positive number';
    }
    
    if (formData.lengthCm && (isNaN(formData.lengthCm) || parseFloat(formData.lengthCm) <= 0)) {
      newErrors.lengthCm = 'Length must be a positive number';
    }
    
    if (formData.widthCm && (isNaN(formData.widthCm) || parseFloat(formData.widthCm) <= 0)) {
      newErrors.widthCm = 'Width must be a positive number';
    }
    
    if (formData.heightCm && (isNaN(formData.heightCm) || parseFloat(formData.heightCm) <= 0)) {
      newErrors.heightCm = 'Height must be a positive number';
    }

    // Validate notification settings if enabled
    if (notificationEnabled) {
      if (!notificationEmail) {
        newErrors.notificationEmail = 'Email is required for notifications';
      } else {
        // Basic email validation
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(notificationEmail)) {
          newErrors.notificationEmail = 'Please enter a valid email address';
        }
      }
      
      if (!stockThreshold) {
        newErrors.stockThreshold = 'Threshold is required for notifications';
      } else if (isNaN(stockThreshold) || stockThreshold < 1) {
        newErrors.stockThreshold = 'Threshold must be a positive number';
      } else if (formData.stockQuantity && stockThreshold > parseInt(formData.stockQuantity)) {
        newErrors.stockThreshold = `Threshold cannot exceed current stock (${formData.stockQuantity})`;
      }
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  // Handle form submission
  const handleSubmit = (e) => {
    e.preventDefault();
    
    if (!validateForm()) {
      setNotification({
        open: true,
        message: 'Please fix the form errors before submitting',
        severity: 'error'
      });
      return;
    }
    
    // Format data for API
    const productData = {
      ...formData,
      price: parseFloat(formData.price),
      stockQuantity: parseInt(formData.stockQuantity),
      weightGrams: formData.weightGrams ? parseFloat(formData.weightGrams) : null,
      lengthCm: formData.lengthCm ? parseFloat(formData.lengthCm) : null,
      widthCm: formData.widthCm ? parseFloat(formData.widthCm) : null,
      heightCm: formData.heightCm ? parseFloat(formData.heightCm) : null,
      tags: formData.tags.map(tag => typeof tag === 'string' ? tag : tag.name)
    };
    
    // Add notification data if enabled
    if (notificationEnabled && !isNewProduct) {
      productData.stockNotification = {
        enabled: true,
        email: notificationEmail,
        threshold: stockThreshold
      };
    }
    
    if (isNewProduct) {
      createProduct.mutate(productData);
    } else {
      updateProduct.mutate({ id, productData });
      
      // Save notification settings separately
      if (notificationEnabled) {
        saveStockNotification.mutate({
          enabled: true,
          email: notificationEmail,
          threshold: stockThreshold
        });
      } else {
        // Disable notifications if checkbox is unchecked
        saveStockNotification.mutate({
          enabled: false,
          email: '',
          threshold: 0
        });
      }
    }
  };
  
  // Handle notification close
  const handleNotificationClose = () => {
    setNotification(prev => ({ ...prev, open: false }));
  };
  
  // Load product data when available
  useEffect(() => {
    if (product && !isNewProduct) {
      // Process images to avoid duplication
      let processedImages = [];
      if (product.images && Array.isArray(product.images)) {
        // Create a Set to track unique paths
        const uniquePaths = new Set();
        processedImages = product.images
          .filter(img => {
            const path = img.path || '';
            if (!path || uniquePaths.has(path)) return false;
            uniquePaths.add(path);
            return true;
          })
          .map((img, index) => ({
            path: img.path || img,
            isPrimary: img.isPrimary || img.is_primary,
            displayOrder: img.displayOrder || img.display_order || index
          }));
      }
    
      setFormData({
        name: product.name || '',
        description: product.description || '',
        categoryName: product.category_name || '',
        price: product.price ? String(product.price) : '',
        stockQuantity: product.stock_quantity !== undefined ? String(product.stock_quantity) : '',
        weightGrams: product.weight_grams ? String(product.weight_grams) : '',
        lengthCm: product.length_cm ? String(product.length_cm) : '',
        widthCm: product.width_cm ? String(product.width_cm) : '',
        heightCm: product.height_cm ? String(product.height_cm) : '',
        origin: product.origin || '',
        age: product.age || '',
        materialType: product.material_type || '',
        color: product.color || '',
        tags: product.tags || [],
        images: processedImages
      });

      // Load notification settings if available
      if (product.stock_notification) {
        setNotificationEnabled(product.stock_notification.enabled);
        setNotificationEmail(product.stock_notification.email || userData?.email || '');
        setStockThreshold(product.stock_notification.threshold || 1);
      } else {
        // Default to admin's email
        setNotificationEmail(userData?.email || '');
      }
    } else {
      // For new products, set default notification email to admin's email
      setNotificationEmail(userData?.email || '');
    }
  }, [product, isNewProduct, userData]);
  
  // Format tag objects for Autocomplete component
  const formatTags = () => {
    if (!allTags) return [];
    return allTags.map(tag => typeof tag === 'string' ? tag : tag.name);
  };

  const isLoading = categoriesLoading || tagsLoading || (productLoading && !isNewProduct);
  const isSaving = createProduct.isLoading || updateProduct.isLoading || saveStockNotification.isLoading;

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (productError && !isNewProduct) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading product: {productError.message}
      </Alert>
    );
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate('/admin/products')}
          sx={{ mr: 2 }}
        >
          Back to Products
        </Button>
        <Typography variant="h4" component="h1">
          {isNewProduct ? 'Add New Product' : 'Edit Product'}
        </Typography>
      </Box>

      <Paper component="form" onSubmit={handleSubmit} sx={{ p: 3 }}>
        <Grid container spacing={3}>
          {/* Basic Information */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Basic Information
            </Typography>
          </Grid>

          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              required
              label="Product Name"
              name="name"
              value={formData.name}
              onChange={handleChange}
              error={!!errors.name}
              helperText={errors.name}
            />
          </Grid>

          <Grid item xs={12} md={6}>
            <FormControl fullWidth required error={!!errors.categoryName}>
              <InputLabel id="category-label">Category</InputLabel>
              <Select
                labelId="category-label"
                name="categoryName"
                value={formData.categoryName}
                onChange={handleChange}
                label="Category"
              >
                {categories?.map((category) => (
                  <MenuItem key={category.id} value={category.name}>
                    {category.name}
                  </MenuItem>
                ))}
              </Select>
              {errors.categoryName && (
                <FormHelperText>{errors.categoryName}</FormHelperText>
              )}
            </FormControl>
          </Grid>

          <Grid item xs={12}>
            <TextField
              fullWidth
              required
              multiline
              rows={4}
              label="Description"
              name="description"
              value={formData.description}
              onChange={handleChange}
              error={!!errors.description}
              helperText={errors.description}
            />
          </Grid>

          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              required
              label="Price"
              name="price"
              type="number"
              value={formData.price}
              onChange={handleChange}
              error={!!errors.price}
              helperText={errors.price}
              InputProps={{
                startAdornment: <InputAdornment position="start">$</InputAdornment>,
              }}
            />
          </Grid>

          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              required
              label="Stock Quantity"
              name="stockQuantity"
              type="number"
              value={formData.stockQuantity}
              onChange={handleChange}
              error={!!errors.stockQuantity}
              helperText={errors.stockQuantity}
            />
          </Grid>

          {/* Stock Notification Section */}
          {!isNewProduct && (
            <>
              <Grid item xs={12}>
                <Divider sx={{ my: 2 }} />
                <Typography variant="h6" gutterBottom>
                  Stock Level Notifications
                </Typography>
              </Grid>

              <Grid item xs={12}>
                <Card variant="outlined" sx={{ bgcolor: 'background.paper' }}>
                  <CardContent>
                    <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                      <NotificationsActiveIcon color="primary" sx={{ mr: 1 }} />
                      <Typography variant="subtitle1">
                        Get notified when stock is running low
                      </Typography>
                    </Box>

                    <FormControlLabel
                      control={
                        <Checkbox
                          checked={notificationEnabled}
                          onChange={handleNotificationToggle}
                          name="notificationEnabled"
                          color="primary"
                        />
                      }
                      label="Enable stock level notifications"
                    />

                    {notificationEnabled && (
                      <Grid container spacing={2} sx={{ mt: 1 }}>
                        <Grid item xs={12} md={6}>
                          <TextField
                            fullWidth
                            label="Notification Email"
                            name="notificationEmail"
                            type="email"
                            value={notificationEmail}
                            onChange={handleNotificationEmailChange}
                            error={!!errors.notificationEmail}
                            helperText={errors.notificationEmail}
                            required
                          />
                        </Grid>
                        <Grid item xs={12} md={6}>
                          <TextField
                            fullWidth
                            label="Stock Threshold"
                            name="stockThreshold"
                            type="number"
                            value={stockThreshold}
                            onChange={handleStockThresholdChange}
                            error={!!errors.stockThreshold}
                            helperText={errors.stockThreshold || "You'll be notified when stock falls below this number"}
                            required
                            InputProps={{
                              inputProps: { 
                                min: 1, 
                                max: formData.stockQuantity ? parseInt(formData.stockQuantity) : 999 
                              }
                            }}
                          />
                        </Grid>
                      </Grid>
                    )}
                  </CardContent>
                </Card>
              </Grid>
            </>
          )}

          <Grid item xs={12}>
            <Divider sx={{ my: 2 }} />
          </Grid>

          {/* Images */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Product Images
            </Typography>
            <Typography variant="body2" color="text.secondary" paragraph>
              Upload images for this product. The first image will be used as the primary image.
            </Typography>
            
            <ImageUploader 
              images={formData.images} 
              onChange={handleImagesChange} 
              multiple={true}
            />
          </Grid>

          <Grid item xs={12}>
            <Divider sx={{ my: 2 }} />
          </Grid>

          {/* Additional Details */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Additional Details
            </Typography>
          </Grid>

          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Material Type"
              name="materialType"
              value={formData.materialType}
              onChange={handleChange}
            />
          </Grid>

          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Color"
              name="color"
              value={formData.color}
              onChange={handleChange}
            />
          </Grid>

          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Origin"
              name="origin"
              value={formData.origin}
              onChange={handleChange}
            />
          </Grid>

          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Age"
              name="age"
              value={formData.age}
              onChange={handleChange}
            />
          </Grid>

          <Grid item xs={12}>
            <Divider sx={{ my: 2 }} />
          </Grid>

          {/* Dimensions */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Dimensions
            </Typography>
          </Grid>

          <Grid item xs={12} sm={6} md={3}>
            <TextField
              fullWidth
              label="Weight (grams)"
              name="weightGrams"
              type="number"
              value={formData.weightGrams}
              onChange={handleChange}
              error={!!errors.weightGrams}
              helperText={errors.weightGrams}
            />
          </Grid>

          <Grid item xs={12} sm={6} md={3}>
            <TextField
              fullWidth
              label="Length (cm)"
              name="lengthCm"
              type="number"
              value={formData.lengthCm}
              onChange={handleChange}
              error={!!errors.lengthCm}
              helperText={errors.lengthCm}
            />
          </Grid>

          <Grid item xs={12} sm={6} md={3}>
            <TextField
              fullWidth
              label="Width (cm)"
              name="widthCm"
              type="number"
              value={formData.widthCm}
              onChange={handleChange}
              error={!!errors.widthCm}
              helperText={errors.widthCm}
            />
          </Grid>

          <Grid item xs={12} sm={6} md={3}>
            <TextField
              fullWidth
              label="Height (cm)"
              name="heightCm"
              type="number"
              value={formData.heightCm}
              onChange={handleChange}
              error={!!errors.heightCm}
              helperText={errors.heightCm}
            />
          </Grid>

          <Grid item xs={12}>
            <Divider sx={{ my: 2 }} />
          </Grid>

          {/* Tags */}
          <Grid item xs={12}>
            <Typography variant="h6" gutterBottom>
              Tags
            </Typography>
            <Typography variant="body2" color="text.secondary" paragraph>
              Add tags to help customers find this product.
            </Typography>
            
            <Autocomplete
              multiple
              freeSolo
              options={formatTags()}
              value={formData.tags}
              onChange={handleTagsChange}
              renderTags={(value, getTagProps) =>
                value.map((option, index) => (
                  <Chip 
                    label={typeof option === 'string' ? option : option.name} 
                    {...getTagProps({ index })} 
                    key={index}
                  />
                ))
              }
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Tags"
                  placeholder="Add tags"
                  helperText="Type and press enter to add new tags"
                />
              )}
            />
          </Grid>

          {/* Submit Button */}
          <Grid item xs={12} sx={{ mt: 3, display: 'flex', justifyContent: 'flex-end' }}>
            <Button
              variant="contained"
              color="primary"
              type="submit"
              disabled={isSaving}
              startIcon={isSaving ? <CircularProgress size={20} /> : <SaveIcon />}
              size="large"
            >
              {isSaving ? 'Saving...' : (isNewProduct ? 'Create Product' : 'Update Product')}
            </Button>
          </Grid>
        </Grid>
      </Paper>

      {/* Notification */}
      <Snackbar
        open={notification.open}
        autoHideDuration={6000}
        onClose={handleNotificationClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
      >
        <Alert 
          onClose={handleNotificationClose} 
          severity={notification.severity}
          sx={{ width: '100%' }}
        >
          {notification.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default ProductEditPage;