import { useEffect, useState } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import PageHeader from '../../components/PageHeader';

interface DashboardMetrics {
    products: {
        total: number;
        low_stock: number;
        out_of_stock: number;
    };
    orders: {
        total: number;
        pending: number;
        this_month: number;
    };
    revenue: {
        this_month: number;
    };
}

export default function StoreDashboard() {
    const [stats, setStats] = useState<DashboardMetrics | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchStats = async () => {
            try {
                const res = await axios.get('/api/store/dashboard');
                setStats(res.data);
            } catch (error) {
                console.error('Error fetching store dashboard:', error);
            } finally {
                setLoading(false);
            }
        };
        fetchStats();
    }, []);

    if (loading) {
        return <div className="loading">Cargando...</div>;
    }

    const metricCards = [
        {
            icon: '📦',
            label: 'Productos Activos',
            value: stats?.products.total || 0,
            gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            glow: 'rgba(102, 126, 234, 0.4)',
        },
        {
            icon: '⚠️',
            label: 'Stock Bajo',
            value: stats?.products.low_stock || 0,
            gradient: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
            glow: 'rgba(250, 112, 154, 0.4)',
        },
        {
            icon: '❌',
            label: 'Sin Stock',
            value: stats?.products.out_of_stock || 0,
            gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
            glow: 'rgba(240, 147, 251, 0.4)',
        },
        {
            icon: '🛒',
            label: 'Órdenes Totales',
            value: stats?.orders.total || 0,
            gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
            glow: 'rgba(79, 172, 254, 0.4)',
        },
        {
            icon: '📋',
            label: 'Pendientes',
            value: stats?.orders.pending || 0,
            gradient: 'linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%)',
            glow: 'rgba(251, 194, 235, 0.4)',
        },
        {
            icon: '💰',
            label: 'Ventas del Mes',
            value: `$${stats?.revenue.this_month?.toLocaleString() || 0}`,
            gradient: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
            glow: 'rgba(67, 233, 123, 0.4)',
        },
    ];

    return (
        <div className="page">
            <PageHeader
                title="🏪 Tienda de Equipos"
                subtitle="Inventario, ventas y garantías"
                actions={
                    <>
                        <Link to="/app/store/products" className="btn btn-secondary">
                            📦 Productos
                        </Link>
                        <Link to="/app/store/orders" className="btn btn-primary">
                            🛒 Nueva Orden
                        </Link>
                    </>
                }
            />

            {/* Metric Cards Grid */}
            <div className="cards-grid">
                {metricCards.map((card, index) => (
                    <div
                        key={index}
                        className="card metric-card"
                        style={{ '--card-glow': card.glow } as React.CSSProperties}
                    >
                        <div
                            className="metric-icon"
                            style={{ background: card.gradient }}
                        >
                            {card.icon}
                        </div>
                        <div className="metric-content">
                            <div className="metric-label">{card.label}</div>
                            <div className="metric-value">{card.value}</div>
                        </div>
                    </div>
                ))}
            </div>

            {/* Quick Actions */}
            <div className="card" style={{ marginTop: '2rem' }}>
                <h3 style={{ marginBottom: '1.5rem' }}>Acciones Rápidas</h3>
                <div style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
                    gap: '1rem',
                }}>
                    <Link to="/app/store/products?filter=low_stock" className="action-card">
                        <span className="action-icon">⚠️</span>
                        <div>
                            <div className="action-title">Revisar Stock Bajo</div>
                            <div className="action-subtitle">Productos que requieren reabastecimiento</div>
                        </div>
                    </Link>
                    <Link to="/app/store/orders?status=pending" className="action-card">
                        <span className="action-icon">📋</span>
                        <div>
                            <div className="action-title">Órdenes Pendientes</div>
                            <div className="action-subtitle">Completar y procesar ventas</div>
                        </div>
                    </Link>
                    <Link to="/app/store/warranties" className="action-card">
                        <span className="action-icon">🛡️</span>
                        <div>
                            <div className="action-title">Garantías Activas</div>
                            <div className="action-subtitle">Gestionar reclamaciones</div>
                        </div>
                    </Link>
                </div>
            </div>
        </div>
    );
}
