import React, { useState, useEffect } from 'react';
import { getNonce } from '../../../Helpers';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, LineChart, Line } from 'recharts';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import WarningIcon from '@mui/icons-material/Warning';
import InfoIcon from '@mui/icons-material/Info';

const CartInteractionsAnalytics = () => {
    const [analytics, setAnalytics] = useState(null);
    const [loading, setLoading] = useState(true);
    const [activeTab, setActiveTab] = useState('overview');
    const [error, setError] = useState(null);
    const [showModal, setShowModal] = useState(false);
    const [modalContent, setModalContent] = useState(null);

    useEffect(() => {
        fetchCartInteractionsAnalytics();
    }, []);

    const fetchCartInteractionsAnalytics = () => {
        setLoading(true);
        setError(null);

        wp.ajax.send('wpnts_get_cart_interactions_analytics', {
            data: {
                nonce: getNonce(),
            },
            success(response) {
                console.log('Cart interactions analytics response:', response);
                
                if (response.success && response.data) {
                    // Handle the response data structure
                    const analyticsData = response.data;
                    
                    // Normalize the data structure
                    const normalizedData = {
                        interaction_counts: analyticsData.interaction_counts || [],
                        product_interactions: analyticsData.product_interactions || [],
                        daily_trends: analyticsData.daily_trends || []
                    };
                    
                    setAnalytics(normalizedData);
                    console.log('Normalized cart interactions:', normalizedData);
                } else if (response.interaction_counts || response.product_interactions || response.daily_trends) {
                    // Handle direct response structure
                    setAnalytics(response);
                    console.log('Direct cart interactions:', response);
                } else {
                    console.warn('No cart interactions data:', response);
                    setAnalytics({
                        interaction_counts: [],
                        product_interactions: [],
                        daily_trends: []
                    });
                }
                setLoading(false);
            },
            error(error) {
                console.error('Failed to fetch cart interactions analytics:', error);
                setError('Failed to load cart interactions data');
                setLoading(false);
            },
        });
    };

    if (loading) {
        return (
            <div className="cart-interactions-analytics">
                <div className="loading-state">
                    <div className="spinner"></div>
                    <p>Loading cart interactions...</p>
                </div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="cart-interactions-analytics">
                <div className="error-state">
                    <WarningIcon className="error-icon" />
                    <p>{error}</p>
                    <button onClick={fetchCartInteractionsAnalytics} className="retry-button">
                        Retry
                    </button>
                </div>
            </div>
        );
    }

    // Check if we have any data
    const hasData = analytics && (
        (analytics.interaction_counts && analytics.interaction_counts.length > 0) ||
        (analytics.product_interactions && analytics.product_interactions.length > 0) ||
        (analytics.daily_trends && analytics.daily_trends.length > 0)
    );

    if (!hasData) {
        return (
            <div className="cart-interactions-analytics">
                <div className="analytics-header">
                    <h2>Cart Interactions Analytics</h2>
                    <p>Track how customers interact with products in their cart</p>
                </div>
                <div className="no-data">
                    <ShoppingCartIcon className="no-data-icon" />
                    <p>No cart interaction data available yet.</p>
                    <p className="no-data-subtext">
                        Data will appear here once customers start interacting with their carts (adding, removing, or changing quantities).
                    </p>
                </div>
            </div>
        );
    }

    const interactionColors = {
        'increase': '#10b981',
        'decrease': '#f59e0b',
        'remove': '#ef4444',
        'add': '#3b82f6',
        'change': '#8b5cf6'
    };

    const interactionLabels = {
        'increase': 'Quantity Increased',
        'decrease': 'Quantity Decreased',
        'remove': 'Removed from Cart',
        'add': 'Added to Cart',
        'change': 'Quantity Changed'
    };

    // Prepare pie chart data
    const pieData = analytics.interaction_counts?.map(item => ({
        name: interactionLabels[item.interaction_type] || item.interaction_type,
        value: parseInt(item.count),
        color: interactionColors[item.interaction_type] || '#6b7280',
        type: item.interaction_type
    })) || [];

    // Calculate totals
    const totalInteractions = analytics.interaction_counts?.reduce((sum, item) => 
        sum + parseInt(item.count), 0
    ) || 0;

    const removalCount = analytics.interaction_counts?.find(item => 
        item.interaction_type === 'remove'
    )?.count || 0;

    const changeCount = analytics.interaction_counts?.filter(item => 
        ['increase', 'decrease', 'change'].includes(item.interaction_type)
    ).reduce((sum, item) => sum + parseInt(item.count), 0) || 0;

    const removalRate = totalInteractions > 0 ? ((removalCount / totalInteractions) * 100).toFixed(1) : 0;
    const engagementRate = totalInteractions > 0 ? ((changeCount / totalInteractions) * 100).toFixed(1) : 0;

    // Find most removed product
    const mostRemovedProduct = analytics.product_interactions?.find(item => 
        item.interaction_type === 'remove'
    );

    // Find most interacted product (any interaction type)
    const mostInteractedProduct = analytics.product_interactions?.reduce((prev, current) => {
        return (parseInt(current.count) > parseInt(prev?.count || 0)) ? current : prev;
    }, null);

    const openModal = (type) => {
        let content = null;
        
        switch (type) {
            case 'interaction-distribution':
                content = {
                    title: 'Interaction Types Distribution',
                    description: 'This chart shows the breakdown of different cart interaction types as percentages of total interactions. It helps identify which actions customers perform most frequently in their cart.',
                    data: pieData,
                    type: 'pie-chart'
                };
                break;
            case 'interaction-breakdown':
                content = {
                    title: 'Interaction Breakdown',
                    description: 'Bar chart showing the count of each interaction type. This helps identify which cart actions are most common among customers and can reveal patterns in shopping behavior.',
                    data: pieData,
                    type: 'bar-chart'
                };
                break;
            case 'product-details':
                content = {
                    title: 'Product Interaction Details',
                    description: 'Detailed breakdown of how customers interact with specific products in their cart. Shows which products get the most attention and what types of interactions they receive.',
                    data: analytics.product_interactions || [],
                    type: 'product-table'
                };
                break;
            case 'daily-trends':
                content = {
                    title: 'Daily Interaction Trends',
                    description: 'Shows how cart interaction patterns change over time. Helps identify peak activity days and customer behavior trends throughout the week.',
                    data: analytics.daily_trends || [],
                    type: 'trends-chart'
                };
                break;
        }
        
        setModalContent(content);
        setShowModal(true);
    };

    const closeModal = () => {
        setShowModal(false);
        setModalContent(null);
    };

    return (
        <div className="cart-interactions-analytics">
            <div className="analytics-header">
                <h2>Cart Interactions Analytics</h2>
                <p>Track how customers interact with products in their cart</p>
            </div>

            <div className="analytics-tabs">
                <button 
                    className={`tab-button ${activeTab === 'overview' ? 'active' : ''}`}
                    onClick={() => setActiveTab('overview')}
                >
                    Overview
                </button>
                <button 
                    className={`tab-button ${activeTab === 'products' ? 'active' : ''}`}
                    onClick={() => setActiveTab('products')}
                >
                    Product Analysis
                </button>
                <button 
                    className={`tab-button ${activeTab === 'trends' ? 'active' : ''}`}
                    onClick={() => setActiveTab('trends')}
                >
                    Daily Trends
                </button>
            </div>

            {activeTab === 'overview' && (
                <div className="overview-tab">
                    <div className="insights-cards">
                        <div className="insight-card">
                            <div className="card-icon-wrapper">
                                <ShoppingCartIcon className="card-icon" />
                            </div>
                            <h3>Total Interactions</h3>
                            <div className="insight-value">{totalInteractions}</div>
                            <p>All cart activities tracked</p>
                        </div>
                        
                        <div className="insight-card">
                            <div className="card-icon-wrapper removal">
                                <WarningIcon className="card-icon" />
                            </div>
                            <h3>Removal Rate</h3>
                            <div className="insight-value">{removalRate}%</div>
                            <p>{removalCount > 0 ? `${removalCount} products removed from cart` : 'No products removed yet'}</p>
                        </div>
                        
                        <div className="insight-card">
                            <div className="card-icon-wrapper engagement">
                                <TrendingUpIcon className="card-icon" />
                            </div>
                            <h3>Engagement Rate</h3>
                            <div className="insight-value">{engagementRate}%</div>
                            <p>{changeCount > 0 ? `${changeCount} quantity adjustments` : 'No quantity changes yet'}</p>
                        </div>
                        
                        <div className="insight-card">
                            <h3>Most Active Product</h3>
                            <div className="insight-value-text">
                                {mostInteractedProduct?.product_name || 'No interactions yet'}
                            </div>
                            <p>{mostInteractedProduct ? `${mostInteractedProduct.count} interactions` : 'No product interactions recorded'}</p>
                        </div>
                    </div>

                    <div className="charts-row">
                        {pieData.length > 0 && (
                            <div className="chart-container">
                                <div className="chart-header">
                                    <h3>Interaction Types Distribution</h3>
                                    <InfoIcon 
                                        className="chart-info-icon" 
                                        onClick={() => openModal('interaction-distribution')}
                                        title="Click for detailed information"
                                    />
                                </div>
                                <ResponsiveContainer width="100%" height={300}>
                                    <PieChart>
                                        <Pie
                                            data={pieData}
                                            cx="50%"
                                            cy="50%"
                                            labelLine={false}
                                            label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                                            outerRadius={80}
                                            fill="#8884d8"
                                            dataKey="value"
                                        >
                                            {pieData.map((entry, index) => (
                                                <Cell key={`cell-${index}`} fill={entry.color} />
                                            ))}
                                        </Pie>
                                        <Tooltip 
                                            formatter={(value) => [`${value} interactions`, 'Count']}
                                        />
                                    </PieChart>
                                </ResponsiveContainer>
                                <div className="chart-legend">
                                    {pieData.map((entry, index) => (
                                        <div key={index} className="legend-item">
                                            <span 
                                                className="legend-color" 
                                                style={{ backgroundColor: entry.color }}
                                            />
                                            <span className="legend-label">{entry.name}</span>
                                            <span className="legend-value">{entry.value}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {analytics.interaction_counts && analytics.interaction_counts.length > 0 && (
                            <div className="chart-container">
                                <div className="chart-header">
                                    <h3>Interaction Breakdown</h3>
                                    <InfoIcon 
                                        className="chart-info-icon" 
                                        onClick={() => openModal('interaction-breakdown')}
                                        title="Click for detailed information"
                                    />
                                </div>
                                <ResponsiveContainer width="100%" height={300}>
                                    <BarChart data={pieData}>
                                        <CartesianGrid strokeDasharray="3 3" />
                                        <XAxis dataKey="name" angle={-45} textAnchor="end" height={100} />
                                        <YAxis />
                                        <Tooltip />
                                        <Bar dataKey="value" name="Count">
                                            {pieData.map((entry, index) => (
                                                <Cell key={`cell-${index}`} fill={entry.color} />
                                            ))}
                                        </Bar>
                                    </BarChart>
                                </ResponsiveContainer>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {activeTab === 'products' && (
                <div className="products-tab">
                    <div className="product-interactions-table">
                        <div className="table-header">
                            <h3>Product Interaction Details</h3>
                            <InfoIcon 
                                className="table-info-icon" 
                                onClick={() => openModal('product-details')}
                                title="Click for detailed information"
                            />
                        </div>
                        {analytics.product_interactions && analytics.product_interactions.length > 0 ? (
                            <table>
                                <thead>
                                    <tr>
                                        <th>Rank</th>
                                        <th>Product Name</th>
                                        <th>Interaction Type</th>
                                        <th>Count</th>
                                        <th>Percentage</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {analytics.product_interactions.map((item, index) => {
                                        const percentage = totalInteractions > 0 
                                            ? ((parseInt(item.count) / totalInteractions) * 100).toFixed(1) 
                                            : 0;
                                        
                                        return (
                                            <tr key={index}>
                                                <td>
                                                    <span className="rank-badge">#{index + 1}</span>
                                                </td>
                                                <td className="product-name-cell">
                                                    <strong>{item.product_name}</strong>
                                                </td>
                                                <td>
                                                    <span 
                                                        className={`interaction-type ${item.interaction_type}`}
                                                        style={{ 
                                                            backgroundColor: interactionColors[item.interaction_type] + '20',
                                                            color: interactionColors[item.interaction_type]
                                                        }}
                                                    >
                                                        {interactionLabels[item.interaction_type] || item.interaction_type}
                                                    </span>
                                                </td>
                                                <td>
                                                    <strong>{item.count}</strong>
                                                </td>
                                                <td>
                                                    <div className="percentage-bar">
                                                        <div 
                                                            className="percentage-fill" 
                                                            style={{ 
                                                                width: `${percentage}%`,
                                                                backgroundColor: interactionColors[item.interaction_type]
                                                            }}
                                                        />
                                                        <span className="percentage-text">{percentage}%</span>
                                                    </div>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        ) : (
                            <div className="no-data">
                                <p>No product interaction data available</p>
                            </div>
                        )}
                    </div>
                </div>
            )}

            {activeTab === 'trends' && (
                <div className="trends-tab">
                    <div className="daily-trends-chart">
                        <div className="chart-header">
                            <h3>Daily Interaction Trends</h3>
                            <InfoIcon 
                                className="chart-info-icon" 
                                onClick={() => openModal('daily-trends')}
                                title="Click for detailed information"
                            />
                        </div>
                        {analytics.daily_trends && analytics.daily_trends.length > 0 ? (
                            <>
                                <ResponsiveContainer width="100%" height={400}>
                                    <LineChart data={analytics.daily_trends}>
                                        <CartesianGrid strokeDasharray="3 3" />
                                        <XAxis dataKey="date" />
                                        <YAxis />
                                        <Tooltip />
                                        <Line 
                                            type="monotone" 
                                            dataKey="count" 
                                            stroke="#3b82f6" 
                                            strokeWidth={2}
                                            name="Interactions"
                                        />
                                    </LineChart>
                                </ResponsiveContainer>
                                
                                <div className="trends-summary">
                                    <h4>Daily Breakdown</h4>
                                    <table>
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Interaction Type</th>
                                                <th>Count</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {analytics.daily_trends.map((trend, index) => (
                                                <tr key={index}>
                                                    <td>{trend.date}</td>
                                                    <td>
                                                        <span 
                                                            className={`interaction-type ${trend.interaction_type}`}
                                                            style={{ 
                                                                backgroundColor: interactionColors[trend.interaction_type] + '20',
                                                                color: interactionColors[trend.interaction_type]
                                                            }}
                                                        >
                                                            {interactionLabels[trend.interaction_type] || trend.interaction_type}
                                                        </span>
                                                    </td>
                                                    <td><strong>{trend.count}</strong></td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </>
                        ) : (
                            <div className="no-data">
                                <p>No daily trends data available</p>
                            </div>
                        )}
                    </div>
                </div>
            )}
            
            {/* Info Modal */}
            {showModal && modalContent && (
                <div className="cart-interactions-modal-overlay" onClick={closeModal}>
                    <div className="cart-interactions-modal" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>{modalContent.title}</h3>
                            <button className="modal-close-btn" onClick={closeModal}>×</button>
                        </div>
                        
                        <div className="modal-content">
                            <div className="modal-description">
                                <p>{modalContent.description}</p>
                            </div>
                            
                            {modalContent.type === 'pie-chart' && modalContent.data.length > 0 && (
                                <div className="modal-chart-section">
                                    <h4>Interaction Distribution</h4>
                                    <div className="modal-chart-container">
                                        <ResponsiveContainer width="100%" height={300}>
                                            <PieChart>
                                                <Pie
                                                    data={modalContent.data}
                                                    cx="50%"
                                                    cy="50%"
                                                    labelLine={false}
                                                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                                                    outerRadius={100}
                                                    fill="#8884d8"
                                                    dataKey="value"
                                                >
                                                    {modalContent.data.map((entry, index) => (
                                                        <Cell key={`cell-${index}`} fill={entry.color} />
                                                    ))}
                                                </Pie>
                                                <Tooltip 
                                                    formatter={(value) => [`${value} interactions`, 'Count']}
                                                />
                                            </PieChart>
                                        </ResponsiveContainer>
                                    </div>
                                    
                                    <div className="modal-stats-grid">
                                        {modalContent.data.map((item, index) => (
                                            <div key={index} className="modal-stat-item">
                                                <div className="stat-color" style={{ backgroundColor: item.color }}></div>
                                                <div className="stat-info">
                                                    <span className="stat-label">{item.name}</span>
                                                    <span className="stat-value">{item.value} interactions</span>
                                                    <span className="stat-percentage">
                                                        {((item.value / modalContent.data.reduce((sum, d) => sum + d.value, 0)) * 100).toFixed(1)}%
                                                    </span>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                            
                            {modalContent.type === 'bar-chart' && modalContent.data.length > 0 && (
                                <div className="modal-chart-section">
                                    <h4>Interaction Counts</h4>
                                    <div className="modal-chart-container">
                                        <ResponsiveContainer width="100%" height={300}>
                                            <BarChart data={modalContent.data}>
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis dataKey="name" angle={-45} textAnchor="end" height={100} />
                                                <YAxis />
                                                <Tooltip />
                                                <Bar dataKey="value" name="Count">
                                                    {modalContent.data.map((entry, index) => (
                                                        <Cell key={`cell-${index}`} fill={entry.color} />
                                                    ))}
                                                </Bar>
                                            </BarChart>
                                        </ResponsiveContainer>
                                    </div>
                                </div>
                            )}
                            
                            {modalContent.type === 'product-table' && modalContent.data.length > 0 && (
                                <div className="modal-table-section">
                                    <h4>Product Interaction Details</h4>
                                    <div className="modal-table-container">
                                        <table className="modal-products-table">
                                            <thead>
                                                <tr>
                                                    <th>Rank</th>
                                                    <th>Product Name</th>
                                                    <th>Interaction Type</th>
                                                    <th>Count</th>
                                                    <th>Percentage</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {modalContent.data.map((item, index) => {
                                                    const totalInteractions = modalContent.data.reduce((sum, d) => sum + parseInt(d.count), 0);
                                                    const percentage = totalInteractions > 0 
                                                        ? ((parseInt(item.count) / totalInteractions) * 100).toFixed(1) 
                                                        : 0;
                                                    
                                                    return (
                                                        <tr key={index}>
                                                            <td className="rank-cell">
                                                                <span className="rank">#{index + 1}</span>
                                                            </td>
                                                            <td className="product-name-cell">
                                                                <strong>{item.product_name}</strong>
                                                            </td>
                                                            <td>
                                                                <span 
                                                                    className={`interaction-type ${item.interaction_type}`}
                                                                    style={{ 
                                                                        backgroundColor: interactionColors[item.interaction_type] + '20',
                                                                        color: interactionColors[item.interaction_type]
                                                                    }}
                                                                >
                                                                    {interactionLabels[item.interaction_type] || item.interaction_type}
                                                                </span>
                                                            </td>
                                                            <td className="count-cell">
                                                                <strong>{item.count}</strong>
                                                            </td>
                                                            <td className="percentage-cell">
                                                                <div className="percentage-bar">
                                                                    <div 
                                                                        className="percentage-fill" 
                                                                        style={{ 
                                                                            width: `${percentage}%`,
                                                                            backgroundColor: interactionColors[item.interaction_type]
                                                                        }}
                                                                    />
                                                                    <span className="percentage-text">{percentage}%</span>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    );
                                                })}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            )}
                            
                            {modalContent.type === 'trends-chart' && modalContent.data.length > 0 && (
                                <div className="modal-chart-section">
                                    <h4>Daily Trends Analysis</h4>
                                    <div className="modal-chart-container">
                                        <ResponsiveContainer width="100%" height={300}>
                                            <LineChart data={modalContent.data}>
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis dataKey="date" />
                                                <YAxis />
                                                <Tooltip />
                                                <Line 
                                                    type="monotone" 
                                                    dataKey="count" 
                                                    stroke="#3b82f6" 
                                                    strokeWidth={2}
                                                    name="Interactions"
                                                />
                                            </LineChart>
                                        </ResponsiveContainer>
                                    </div>
                                    
                                    <div className="modal-trends-summary">
                                        <h5>Trends Summary</h5>
                                        <div className="trends-stats">
                                            <div className="trend-stat">
                                                <span className="trend-label">Total Days:</span>
                                                <span className="trend-value">{modalContent.data.length}</span>
                                            </div>
                                            <div className="trend-stat">
                                                <span className="trend-label">Total Interactions:</span>
                                                <span className="trend-value">
                                                    {modalContent.data.reduce((sum, d) => sum + parseInt(d.count), 0)}
                                                </span>
                                            </div>
                                            <div className="trend-stat">
                                                <span className="trend-label">Average per Day:</span>
                                                <span className="trend-value">
                                                    {(modalContent.data.reduce((sum, d) => sum + parseInt(d.count), 0) / modalContent.data.length).toFixed(1)}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                        
                        <div className="modal-footer">
                            <button className="btn btn-default" onClick={closeModal}>
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default CartInteractionsAnalytics;