import React, { useState, useEffect } from 'react';
import api from '../utils/api';

const VariationModal = ({ 
    open, 
    onClose, 
    productId,
    variation = null,
    attributes = [],
    onSave,
    showError,
    showSuccess 
}) => {
    const [loading, setLoading] = useState(false);
    const [variationData, setVariationData] = useState({
        sku: '',
        gtin: '',
        upc: '',
        ean: '',
        isbn: '',
        enabled: true,
        downloadable: false,
        virtual: false,
        manage_stock: false,
        regular_price: '',
        sale_price: '',
        sale_date_from: '',
        sale_date_to: '',
        weight: '',
        length: '',
        width: '',
        height: '',
        shipping_class: '',
        description: '',
        attributes: {}
    });

    const [shippingClasses, setShippingClasses] = useState([]);

    useEffect(() => {
        if (open) {
            loadShippingClasses();
            if (variation) {
                // Edit mode - populate with existing variation data
                setVariationData({
                    sku: variation.sku || '',
                    gtin: variation.gtin || '',
                    upc: variation.upc || '',
                    ean: variation.ean || '',
                    isbn: variation.isbn || '',
                    enabled: variation.enabled !== false,
                    downloadable: variation.downloadable || false,
                    virtual: variation.virtual || false,
                    manage_stock: variation.manage_stock || false,
                    regular_price: variation.regular_price || '',
                    sale_price: variation.sale_price || '',
                    sale_date_from: variation.sale_date_from || '',
                    sale_date_to: variation.sale_date_to || '',
                    weight: variation.weight || '',
                    length: variation.dimensions?.length || '',
                    width: variation.dimensions?.width || '',
                    height: variation.dimensions?.height || '',
                    shipping_class: variation.shipping_class || '',
                    description: variation.description || '',
                    attributes: variation.attributes || {}
                });
            } else {
                // Create mode - initialize with default attribute values
                const defaultAttributes = {};
                attributes.forEach(attr => {
                    if (attr.terms && attr.terms.length > 0) {
                        defaultAttributes[attr.name] = attr.terms[0].name;
                    }
                });
                setVariationData(prev => ({
                    ...prev,
                    attributes: defaultAttributes
                }));
            }
        }
    }, [open, variation, attributes]);

    const loadShippingClasses = async () => {
        try {
            const response = await api.get('/woocommerce/products/shipping_classes');
            if (response.success) {
                setShippingClasses(response.shipping_classes || []);
            }
        } catch (error) {
            console.error('Error loading shipping classes:', error);
        }
    };

    const handleInputChange = (field, value) => {
        setVariationData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const handleAttributeChange = (attributeName, value) => {
        setVariationData(prev => ({
            ...prev,
            attributes: {
                ...prev.attributes,
                [attributeName]: value
            }
        }));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);

        try {
            // Validate required fields
            if (!variationData.regular_price && !variationData.sale_price) {
                throw new Error('At least one price (regular or sale) is required');
            }

            // Prepare variation data
            const submitData = {
                ...variationData,
                dimensions: {
                    length: variationData.length,
                    width: variationData.width,
                    height: variationData.height
                }
            };

            // Remove individual dimension fields
            delete submitData.length;
            delete submitData.width;
            delete submitData.height;

            let response;
            if (variation) {
                // Update existing variation
                response = await api.put(`/products/${productId}/variations/${variation.id}`, submitData);
            } else {
                // Create new variation
                response = await api.post(`/products/${productId}/variations`, submitData);
            }

            if (response.success) {
                showSuccess(variation ? 'Variation updated successfully' : 'Variation created successfully');
                onSave(response.variation);
                onClose();
            } else {
                throw new Error(response.message || 'Failed to save variation');
            }
        } catch (error) {
            showError(error.message);
        } finally {
            setLoading(false);
        }
    };

    if (!open) return null;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content modal-large" onClick={(e) => e.stopPropagation()}>
                <div className="modal-header">
                    <h3>{variation ? 'Edit Variation' : 'Add New Variation'}</h3>
                    <button type="button" className="modal-close" onClick={onClose}>
                        ✕
                    </button>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="modal-body">
                        {/* Attributes Selection */}
                        <div className="form-section">
                            <h4>Variation Attributes</h4>
                            <div className="grid grid-cols-2 gap-4">
                                {attributes.map(attribute => (
                                    <div key={attribute.id} className="form-group">
                                        <label>{attribute.name}</label>
                                        <select
                                            value={variationData.attributes[attribute.name] || ''}
                                            onChange={(e) => handleAttributeChange(attribute.name, e.target.value)}
                                            required
                                        >
                                            <option value="">Choose {attribute.name}</option>
                                            {attribute.terms?.map(term => (
                                                <option key={term.id} value={term.name}>
                                                    {term.name}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                ))}
                            </div>
                        </div>

                        {/* Basic Information */}
                        <div className="form-section">
                            <h4>Basic Information</h4>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="form-group">
                                    <label>SKU</label>
                                    <input
                                        type="text"
                                        value={variationData.sku}
                                        onChange={(e) => handleInputChange('sku', e.target.value)}
                                        placeholder="Enter SKU"
                                    />
                                </div>
                                <div className="form-group">
                                    <label>GTIN, UPC, EAN, or ISBN</label>
                                    <input
                                        type="text"
                                        value={variationData.gtin || variationData.upc || variationData.ean || variationData.isbn}
                                        onChange={(e) => handleInputChange('gtin', e.target.value)}
                                        placeholder="Enter product identifier"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-3 gap-4">
                                <div className="form-group">
                                    <label className="checkbox-label">
                                        <input
                                            type="checkbox"
                                            checked={variationData.enabled}
                                            onChange={(e) => handleInputChange('enabled', e.target.checked)}
                                        />
                                        Enabled
                                    </label>
                                </div>
                                <div className="form-group">
                                    <label className="checkbox-label">
                                        <input
                                            type="checkbox"
                                            checked={variationData.downloadable}
                                            onChange={(e) => handleInputChange('downloadable', e.target.checked)}
                                        />
                                        Downloadable
                                    </label>
                                </div>
                                <div className="form-group">
                                    <label className="checkbox-label">
                                        <input
                                            type="checkbox"
                                            checked={variationData.virtual}
                                            onChange={(e) => handleInputChange('virtual', e.target.checked)}
                                        />
                                        Virtual
                                    </label>
                                </div>
                            </div>
                        </div>

                        {/* Inventory */}
                        <div className="form-section">
                            <h4>Inventory</h4>
                            <div className="form-group">
                                <label className="checkbox-label">
                                    <input
                                        type="checkbox"
                                        checked={variationData.manage_stock}
                                        onChange={(e) => handleInputChange('manage_stock', e.target.checked)}
                                    />
                                    Manage stock?
                                </label>
                            </div>
                            {variationData.manage_stock && (
                                <div className="form-group">
                                    <label>Stock Quantity</label>
                                    <input
                                        type="number"
                                        value={variationData.stock_quantity || ''}
                                        onChange={(e) => handleInputChange('stock_quantity', e.target.value)}
                                        placeholder="Enter stock quantity"
                                    />
                                </div>
                            )}
                        </div>

                        {/* Pricing */}
                        <div className="form-section">
                            <h4>Pricing</h4>
                            <div className="grid grid-cols-2 gap-4">
                                <div className="form-group">
                                    <label>Regular Price ($) *</label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        value={variationData.regular_price}
                                        onChange={(e) => handleInputChange('regular_price', e.target.value)}
                                        placeholder="0.00"
                                        required
                                    />
                                </div>
                                <div className="form-group">
                                    <label>Sale Price ($)</label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        value={variationData.sale_price}
                                        onChange={(e) => handleInputChange('sale_price', e.target.value)}
                                        placeholder="0.00"
                                    />
                                </div>
                            </div>

                            {variationData.sale_price && (
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="form-group">
                                        <label>Sale Start Date</label>
                                        <input
                                            type="date"
                                            value={variationData.sale_date_from}
                                            onChange={(e) => handleInputChange('sale_date_from', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Sale End Date</label>
                                        <input
                                            type="date"
                                            value={variationData.sale_date_to}
                                            onChange={(e) => handleInputChange('sale_date_to', e.target.value)}
                                        />
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Shipping - Hide if virtual */}
                        {!variationData.virtual && (
                            <div className="form-section">
                                <h4>Shipping</h4>
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="form-group">
                                        <label>Weight (lbs)</label>
                                        <input
                                            type="number"
                                            step="0.01"
                                            value={variationData.weight}
                                            onChange={(e) => handleInputChange('weight', e.target.value)}
                                            placeholder="0.00"
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Shipping Class</label>
                                        <select
                                            value={variationData.shipping_class}
                                            onChange={(e) => handleInputChange('shipping_class', e.target.value)}
                                        >
                                            <option value="">Same as parent</option>
                                            {shippingClasses.map(shippingClass => (
                                                <option key={shippingClass.id} value={shippingClass.slug}>
                                                    {shippingClass.name}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label>Dimensions (L×W×H) (in)</label>
                                    <div className="grid grid-cols-3 gap-2">
                                        <input
                                            type="number"
                                            step="0.01"
                                            value={variationData.length}
                                            onChange={(e) => handleInputChange('length', e.target.value)}
                                            placeholder="Length"
                                        />
                                        <input
                                            type="number"
                                            step="0.01"
                                            value={variationData.width}
                                            onChange={(e) => handleInputChange('width', e.target.value)}
                                            placeholder="Width"
                                        />
                                        <input
                                            type="number"
                                            step="0.01"
                                            value={variationData.height}
                                            onChange={(e) => handleInputChange('height', e.target.value)}
                                            placeholder="Height"
                                        />
                                    </div>
                                </div>
                            </div>
                        )}

                        {/* Description */}
                        <div className="form-section">
                            <h4>Description</h4>
                            <div className="form-group">
                                <textarea
                                    value={variationData.description}
                                    onChange={(e) => handleInputChange('description', e.target.value)}
                                    placeholder="Enter variation description"
                                    rows="4"
                                />
                            </div>
                        </div>
                    </div>

                    <div className="modal-footer">
                        <button
                            type="button"
                            className="btn btn-secondary"
                            onClick={onClose}
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            className={`btn btn-primary ${loading ? 'btn-loading' : ''}`}
                            disabled={loading}
                        >
                            {loading ? 'Saving...' : (variation ? 'Update Variation' : 'Create Variation')}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default VariationModal;