import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Paper,
  TextField,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  FormHelperText,
  Switch,
  FormControlLabel,
  Grid,
  Button,
  IconButton,
  CircularProgress,
  Alert,
  Divider,
  InputAdornment,
  Autocomplete,
  Chip,
  Breadcrumbs,
  Link
} from '@mui/material';
import {
  ArrowBack as ArrowBackIcon,
  Save as SaveIcon,
  Clear as ClearIcon
} from '@mui/icons-material';
import { useNavigate, useParams, Link as RouterLink } from 'react-router-dom';
import { useAdminCoupon, useCreateCoupon, useUpdateCoupon } from '@hooks/couponAdminHooks';
import { useCategories, useTags } from '@hooks/apiHooks';
import { format, parseISO } from 'date-fns';

const CouponEditPage = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const isNewCoupon = !id;
  
  // Form state
  const [formData, setFormData] = useState({
    code: '',
    description: '',
    discountType: 'percentage', // 'percentage' or 'fixed_amount'
    discountValue: '',
    minPurchaseAmount: '',
    maxDiscountAmount: '',
    redemptionLimit: '',
    startDate: null,
    endDate: null,
    isActive: true,
    categories: [],
    tags: [],
    blacklistedProducts: []
  });
  
  // Validation state
  const [errors, setErrors] = useState({});
  
  // Notification state
  const [notification, setNotification] = useState({
    open: false,
    message: '',
    severity: 'success'
  });
  
  // Fetch coupon data for editing
  const { data: coupon, isLoading: couponLoading, error: couponError } = useAdminCoupon(
    isNewCoupon ? null : id
  );
  
  // Mutations
  const createCoupon = useCreateCoupon();
  const updateCoupon = useUpdateCoupon();
  
  // Fetch categories and tags
  const { data: categories } = useCategories();
  const { data: tags } = useTags();
  
  // Set form data when editing existing coupon
  useEffect(() => {
    if (!isNewCoupon && coupon) {
      setFormData({
        code: coupon.code || '',
        description: coupon.description || '',
        discountType: coupon.discount_type || 'percentage',
        discountValue: coupon.discount_value?.toString() || '',
        minPurchaseAmount: coupon.min_purchase_amount?.toString() || '',
        maxDiscountAmount: coupon.max_discount_amount?.toString() || '',
        redemptionLimit: coupon.redemption_limit?.toString() || '',
        startDate: coupon.start_date ? parseISO(coupon.start_date) : null,
        endDate: coupon.end_date ? parseISO(coupon.end_date) : null,
        isActive: coupon.is_active ?? true,
        categories: coupon.categories || [],
        tags: coupon.tags || [],
        blacklistedProducts: coupon.blacklisted_products || []
      });
    }
  }, [isNewCoupon, coupon]);
  
  // Handle form changes
  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
    
    // Clear validation error when field is edited
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
  };

  
  // Handle date changes
  const handleDateChange = (name, date) => {
    setFormData(prev => ({
      ...prev,
      [name]: date
    }));
    
    // Clear validation error when field is edited
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
  };
  
  // Handle categories change
  const handleCategoriesChange = (event, newValue) => {
    setFormData(prev => ({
      ...prev,
      categories: newValue
    }));
  };
  
  // Handle tags change
  const handleTagsChange = (event, newValue) => {
    setFormData(prev => ({
      ...prev,
      tags: newValue
    }));
  };
  
  // Validate form
  const validateForm = () => {
    const newErrors = {};
    
    // Required fields
    if (!formData.code) {
      newErrors.code = 'Coupon code is required';
    } else if (!/^[A-Za-z0-9_-]+$/.test(formData.code)) {
      newErrors.code = 'Code can only contain letters, numbers, underscores, and hyphens';
    }
    
    if (!formData.discountType) {
      newErrors.discountType = 'Discount type is required';
    }
    
    if (!formData.discountValue) {
      newErrors.discountValue = 'Discount value is required';
    } else if (isNaN(formData.discountValue) || parseFloat(formData.discountValue) <= 0) {
      newErrors.discountValue = 'Discount value must be a positive number';
    } else if (formData.discountType === 'percentage' && parseFloat(formData.discountValue) > 100) {
      newErrors.discountValue = 'Percentage discount cannot exceed 100%';
    }
    
    // Optional numeric fields
    if (formData.minPurchaseAmount && (isNaN(formData.minPurchaseAmount) || parseFloat(formData.minPurchaseAmount) < 0)) {
      newErrors.minPurchaseAmount = 'Minimum purchase amount must be a non-negative number';
    }
    
    if (formData.maxDiscountAmount && (isNaN(formData.maxDiscountAmount) || parseFloat(formData.maxDiscountAmount) <= 0)) {
      newErrors.maxDiscountAmount = 'Maximum discount amount must be a positive number';
    }
    
    if (formData.redemptionLimit && (isNaN(formData.redemptionLimit) || parseInt(formData.redemptionLimit) <= 0 || !Number.isInteger(parseFloat(formData.redemptionLimit)))) {
      newErrors.redemptionLimit = 'Redemption limit must be a positive integer';
    }
    
    // Date validation
    if (formData.startDate && formData.endDate && formData.startDate > formData.endDate) {
      newErrors.endDate = 'End date must be after start date';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!validateForm()) {
      setNotification({
        open: true,
        message: 'Please fix the form errors before submitting',
        severity: 'error'
      });
      return;
    }
    
    // Format date fields
    const formattedData = {
      ...formData,
      code: formData.code.toUpperCase(),
      discountValue: parseFloat(formData.discountValue),
      minPurchaseAmount: formData.minPurchaseAmount ? parseFloat(formData.minPurchaseAmount) : null,
      maxDiscountAmount: formData.maxDiscountAmount ? parseFloat(formData.maxDiscountAmount) : null,
      redemptionLimit: formData.redemptionLimit ? parseInt(formData.redemptionLimit) : null,
      startDate: formData.startDate ? format(formData.startDate, "yyyy-MM-dd'T'HH:mm:ss") : null,
      endDate: formData.endDate ? format(formData.endDate, "yyyy-MM-dd'T'HH:mm:ss") : null,
      // Format arrays for API
      categories: formData.categories.map(cat => cat.id),
      tags: formData.tags.map(tag => tag.id),
      blacklistedProducts: formData.blacklistedProducts.map(prod => prod.id)
    };
    
    try {
      if (isNewCoupon) {
        await createCoupon.mutateAsync(formattedData);
        setNotification({
          open: true,
          message: 'Coupon created successfully',
          severity: 'success'
        });
        
        // Navigate after successful creation
        setTimeout(() => {
          navigate('/admin/coupons');
        }, 1500);
      } else {
        await updateCoupon.mutateAsync({
          id,
          couponData: formattedData
        });
        
        setNotification({
          open: true,
          message: 'Coupon updated successfully',
          severity: 'success'
        });
      }
    } catch (error) {
      setNotification({
        open: true,
        message: error.message || 'Error saving coupon',
        severity: 'error'
      });
    }
  };
  
  // Handle notification close
  const handleNotificationClose = () => {
    setNotification(prev => ({ ...prev, open: false }));
  };
  
  // Loading state
  if ((!isNewCoupon && couponLoading) || (!categories || !tags)) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }
  
  // Error state
  if (!isNewCoupon && couponError) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading coupon: {couponError.message}
      </Alert>
    );
  }
  
  return (
    <Box>
      <Box sx={{ mb: 3 }}>
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate('/admin/coupons')}
          sx={{ mb: 2 }}
        >
          Back to Coupons
        </Button>
        
        <Breadcrumbs sx={{ mb: 2 }}>
          <Link component={RouterLink} to="/admin" color="inherit">
            Admin
          </Link>
          <Link component={RouterLink} to="/admin/coupons" color="inherit">
            Coupons
          </Link>
          <Typography color="text.primary">
            {isNewCoupon ? 'Create Coupon' : 'Edit Coupon'}
          </Typography>
        </Breadcrumbs>
        
        <Typography variant="h4" component="h1" gutterBottom>
          {isNewCoupon ? 'Create New Coupon' : `Edit Coupon: ${coupon?.code || "Enter Code"}`}
        </Typography>
      </Box>
      
      {/* Form */}
      <Paper component="form" onSubmit={handleSubmit} sx={{ p: 3 }}>
        {notification.open && (
          <Alert 
            severity={notification.severity} 
            sx={{ mb: 3 }}
            onClose={handleNotificationClose}
          >
            {notification.message}
          </Alert>
        )}
        
        <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="Coupon Code"
              name="code"
              value={formData.code}
              onChange={handleChange}
              error={!!errors.code}
              helperText={errors.code || 'Use uppercase letters, numbers, and hyphens'}
              inputProps={{ style: { textTransform: 'uppercase' } }}
              disabled={!isNewCoupon} // Cannot edit code for existing coupons
            />
          </Grid>
          
          <Grid item xs={12} md={6}>
            <FormControlLabel
              control={
                <Switch
                  checked={formData.isActive}
                  onChange={handleChange}
                  name="isActive"
                  color="primary"
                />
              }
              label={formData.isActive ? 'Coupon is Active' : 'Coupon is Inactive'}
            />
          </Grid>
          
          <Grid item xs={12}>
            <TextField
              fullWidth
              label="Description"
              name="description"
              value={formData.description}
              onChange={handleChange}
              multiline
              rows={2}
              placeholder="Optional description of the coupon and its usage"
            />
          </Grid>
          
          {/* Discount Settings */}
          <Grid item xs={12}>
            <Divider sx={{ my: 1 }} />
            <Typography variant="h6" gutterBottom>
              Discount Settings
            </Typography>
          </Grid>
          
          <Grid item xs={12} md={6}>
            <FormControl fullWidth required error={!!errors.discountType}>
              <InputLabel id="discount-type-label">Discount Type</InputLabel>
              <Select
                labelId="discount-type-label"
                name="discountType"
                value={formData.discountType}
                label="Discount Type"
                onChange={handleChange}
              >
                <MenuItem value="percentage">Percentage</MenuItem>
                <MenuItem value="fixed_amount">Fixed Amount</MenuItem>
              </Select>
              {errors.discountType && <FormHelperText>{errors.discountType}</FormHelperText>}
            </FormControl>
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              required
              label="Discount Value"
              name="discountValue"
              type="number"
              value={formData.discountValue}
              onChange={handleChange}
              error={!!errors.discountValue}
              helperText={errors.discountValue}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    {formData.discountType === 'percentage' ? '%' : ''}
                  </InputAdornment>
                ),
              }}
            />
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Minimum Purchase Amount"
              name="minPurchaseAmount"
              type="number"
              value={formData.minPurchaseAmount}
              onChange={handleChange}
              error={!!errors.minPurchaseAmount}
              helperText={errors.minPurchaseAmount || 'Minimum cart total to use this coupon (optional)'}
              InputProps={{
                startAdornment: <InputAdornment position="start">$</InputAdornment>,
              }}
            />
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Maximum Discount Amount"
              name="maxDiscountAmount"
              type="number"
              value={formData.maxDiscountAmount}
              onChange={handleChange}
              error={!!errors.maxDiscountAmount}
              helperText={errors.maxDiscountAmount || 'Maximum discount for percentage coupons (optional)'}
              InputProps={{
                startAdornment: <InputAdornment position="start">$</InputAdornment>,
              }}
              disabled={formData.discountType !== 'percentage'}
            />
          </Grid>
          
          {/* Validity and Usage */}
          <Grid item xs={12}>
            <Divider sx={{ my: 1 }} />
            <Typography variant="h6" gutterBottom>
              Validity and Usage Limits
            </Typography>
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Start Date (Optional)"
              name="startDate"
              type="date"
              value={formData.startDate}
              onChange={handleChange}
              error={!!errors.startDate}
              helperText={errors.startDate || 'When this coupon becomes valid'}
              InputLabelProps={{
                shrink: true,
              }}
            />
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="End Date (Optional)"
              name="endDate"
              type="date"
              value={formData.endDate}
              onChange={handleChange}
              error={!!errors.endDate}
              helperText={errors.endDate || 'When this coupon expires'}
              InputLabelProps={{
                shrink: true,
              }}
            />
          </Grid>
          
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Redemption Limit"
              name="redemptionLimit"
              type="number"
              value={formData.redemptionLimit}
              onChange={handleChange}
              error={!!errors.redemptionLimit}
              helperText={errors.redemptionLimit || 'How many times this coupon can be used (optional, leave empty for unlimited)'}
            />
          </Grid>
          
          {/* Applicable Categories and Tags */}
          <Grid item xs={12}>
            <Divider sx={{ my: 1 }} />
            <Typography variant="h6" gutterBottom>
              Applicable Products
            </Typography>
            <Typography variant="body2" color="text.secondary" paragraph>
              Specify which categories or tags this coupon applies to. If none selected, coupon applies to all products.
            </Typography>
          </Grid>
          
          <Grid item xs={12} md={6}>
            <Autocomplete
              multiple
              options={categories || []}
              getOptionLabel={(option) => option.name}
              isOptionEqualToValue={(option, value) => option.id === value.id}
              value={formData.categories}
              onChange={handleCategoriesChange}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Applicable Categories"
                  placeholder="Select categories"
                />
              )}
              renderTags={(selected, getTagProps) =>
                selected.map((category, index) => (
                  <Chip
                    label={category.name}
                    {...getTagProps({ index })}
                    key={category.id}
                  />
                ))
              }
            />
          </Grid>
          
          <Grid item xs={12} md={6}>
            <Autocomplete
              multiple
              options={tags || []}
              getOptionLabel={(option) => option.name}
              isOptionEqualToValue={(option, value) => option.id === value.id}
              value={formData.tags}
              onChange={handleTagsChange}
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Applicable Tags"
                  placeholder="Select tags"
                />
              )}
              renderTags={(selected, getTagProps) =>
                selected.map((tag, index) => (
                  <Chip
                    label={tag.name}
                    {...getTagProps({ index })}
                    key={tag.id}
                  />
                ))
              }
            />
          </Grid>
          
          {/* Submit Button */}
          <Grid item xs={12} sx={{ mt: 3 }}>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              startIcon={
                createCoupon.isLoading || updateCoupon.isLoading
                  ? <CircularProgress size={24} color="inherit" />
                  : <SaveIcon />
              }
              disabled={createCoupon.isLoading || updateCoupon.isLoading}
            >
              {isNewCoupon ? 'Create Coupon' : 'Update Coupon'}
            </Button>
            
            <Button
              variant="outlined"
              sx={{ ml: 2 }}
              onClick={() => navigate('/admin/coupons')}
            >
              Cancel
            </Button>
          </Grid>
        </Grid>
      </Paper>
    </Box>
  );
};


export default CouponEditPage;