import React, { useState, useEffect } from 'react';
import VariationModal from './VariationModal';
import VariationGenerateModal from './VariationGenerateModal';
import ConfirmDialog from './ConfirmDialog';
import api from '../utils/api';
import './VariationsTab.css';

const VariationsTab = ({
    productId,
    productType,
    attributes = [],
    showError,
    showSuccess
}) => {
    const [variations, setVariations] = useState([]);
    const [loading, setLoading] = useState(false);
    const [showVariationModal, setShowVariationModal] = useState(false);
    const [showGenerateModal, setShowGenerateModal] = useState(false);
    const [editingVariation, setEditingVariation] = useState(null);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [variationToDelete, setVariationToDelete] = useState(null);

    useEffect(() => {
        if (productId && productType === 'variable') {
            loadVariations();
        }
    }, [productId, productType]);

    const loadVariations = async () => {
        setLoading(true);
        try {
            const response = await api.get(`/products/${productId}/variations`);
            if (response.success) {
                setVariations(response.variations || []);
            }
        } catch (error) {
            console.error('Error loading variations:', error);
            showError('Failed to load variations');
        } finally {
            setLoading(false);
        }
    };

    const handleGenerateVariations = async () => {
        try {
            const response = await api.post(`/products/${productId}/variations/generate`, {
                attributes: attributes.map(attr => ({
                    id: attr.id,
                    name: attr.name,
                    terms: attr.terms || []
                }))
            });

            if (response.success) {
                await loadVariations();
                return response;
            } else {
                throw new Error(response.message || 'Failed to generate variations');
            }
        } catch (error) {
            throw error;
        }
    };

    const handleSaveVariation = async (variationData) => {
        await loadVariations();
    };

    const handleEditVariation = (variation) => {
        setEditingVariation(variation);
        setShowVariationModal(true);
    };

    const handleDeleteVariation = (variationId) => {
        setVariationToDelete(variationId);
        setDeleteDialogOpen(true);
    };

    const confirmDeleteVariation = async () => {
        if (!variationToDelete) return;

        try {
            const response = await api.delete(`/products/${productId}/variations/${variationToDelete}`);
            if (response.success) {
                showSuccess('Variation deleted successfully');
                await loadVariations();
            } else {
                throw new Error(response.message || 'Failed to delete variation');
            }
        } catch (error) {
            showError(error.message);
        } finally {
            setDeleteDialogOpen(false);
            setVariationToDelete(null);
        }
    };

    const handleAddManually = () => {
        setEditingVariation(null);
        setShowVariationModal(true);
    };

    const formatPrice = (price) => {
        return price ? `$${parseFloat(price).toFixed(2)}` : '-';
    };

    const formatAttributes = (variationAttributes) => {
        if (!variationAttributes || typeof variationAttributes !== 'object') {
            return '-';
        }

        return Object.entries(variationAttributes)
            .map(([name, value]) => `${name}: ${value}`)
            .join(', ');
    };

    if (productType !== 'variable') {
        return (
            <div className="variations-tab">
                <div className="no-variations">
                    <p>Variations are only available for Variable products.</p>
                    <p>Change the product type to "Variable Product" to manage variations.</p>
                </div>
            </div>
        );
    }

    if (!attributes || attributes.length === 0) {
        return (
            <div className="variations-tab">
                <div className="no-attributes">
                    <h4>No Attributes Found</h4>
                    <p>You need to add product attributes before creating variations.</p>
                    <p>Go to the Attributes tab to add attributes for this product.</p>
                </div>
            </div>
        );
    }

    return (
        <div className="variations-tab">
            <div className="variations-header">
                <h4>Product Variations</h4>
                <div className="variations-actions">
                    <button
                        type="button"
                        className="btn btn-secondary"
                        onClick={() => setShowGenerateModal(true)}
                        disabled={loading}
                    >
                        Generate Variations
                    </button>
                    <button
                        type="button"
                        className="btn btn-primary"
                        onClick={handleAddManually}
                        disabled={loading}
                    >
                        Add Manually
                    </button>
                </div>
            </div>

            {loading ? (
                <div className="loading-state">
                    <p>Loading variations...</p>
                </div>
            ) : (
                <>
                    {variations.length === 0 ? (
                        <div className="no-variations">
                            <p>No variations found for this product.</p>
                            <p>Use "Generate Variations" to create all possible combinations, or "Add Manually" to create specific variations.</p>
                        </div>
                    ) : (
                        <div className="variations-list">
                            <div className="variations-table">
                                <div className="table-header">
                                    <div className="col-image">Image</div>
                                    <div className="col-attributes">Attributes</div>
                                    <div className="col-sku">SKU</div>
                                    <div className="col-price">Price</div>
                                    <div className="col-stock">Stock</div>
                                    <div className="col-enabled">Enabled</div>
                                    <div className="col-actions">Actions</div>
                                </div>

                                {variations.map(variation => (
                                    <div key={variation.id} className="table-row">
                                        <div className="col-image">
                                            {variation.image ? (
                                                <img
                                                    src={variation.image.src}
                                                    alt={variation.image.alt}
                                                    className="variation-image"
                                                />
                                            ) : (
                                                <div className="no-image">📦</div>
                                            )}
                                        </div>
                                        <div className="col-attributes">
                                            {formatAttributes(variation.attributes)}
                                        </div>
                                        <div className="col-sku">
                                            {variation.sku || '-'}
                                        </div>
                                        <div className="col-price">
                                            <div className="price-info">
                                                <div className="regular-price">
                                                    {formatPrice(variation.regular_price)}
                                                </div>
                                                {variation.sale_price && (
                                                    <div className="sale-price">
                                                        Sale: {formatPrice(variation.sale_price)}
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                        <div className="col-stock">
                                            {variation.manage_stock ? (
                                                <span className={`stock-status ${variation.stock_status}`}>
                                                    {variation.stock_quantity || 0}
                                                </span>
                                            ) : (
                                                <span className="stock-status in-stock">
                                                    {variation.stock_status}
                                                </span>
                                            )}
                                        </div>
                                        <div className="col-enabled">
                                            <span className={`status-badge ${variation.enabled ? 'enabled' : 'disabled'}`}>
                                                {variation.enabled ? 'Yes' : 'No'}
                                            </span>
                                        </div>
                                        <div className="col-actions">
                                            <button
                                                type="button"
                                                className="btn btn-sm btn-secondary"
                                                onClick={() => handleEditVariation(variation)}
                                                title="Edit variation"
                                            >
                                                ✏️
                                            </button>
                                            <button
                                                type="button"
                                                className="btn btn-sm btn-danger"
                                                onClick={() => handleDeleteVariation(variation.id)}
                                                title="Delete variation"
                                            >
                                                🗑️
                                            </button>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </>
            )}

            {/* Variation Modal */}
            <VariationModal
                open={showVariationModal}
                onClose={() => {
                    setShowVariationModal(false);
                    setEditingVariation(null);
                }}
                productId={productId}
                variation={editingVariation}
                attributes={attributes}
                onSave={handleSaveVariation}
                showError={showError}
                showSuccess={showSuccess}
            />

            {/* Generate Variations Modal */}
            <VariationGenerateModal
                open={showGenerateModal}
                onClose={() => setShowGenerateModal(false)}
                attributes={attributes}
                onGenerate={handleGenerateVariations}
                showError={showError}
                showSuccess={showSuccess}
            />

            {/* Delete Confirmation Dialog */}
            <ConfirmDialog
                isOpen={deleteDialogOpen}
                onClose={() => {
                    setDeleteDialogOpen(false);
                    setVariationToDelete(null);
                }}
                onConfirm={confirmDeleteVariation}
                title="Confirm Delete"
                confirmText="Delete Variation"
                confirmButtonClass="btn-danger"
            >
                <p>Are you sure you want to delete this variation?</p>
                <p className="text-danger">This action cannot be undone.</p>
            </ConfirmDialog>

        </div>
    );
};

export default VariationsTab;