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

interface DashboardStats {
    activeProjects: number;
    activeSprints: number;
    blockedItems: number;
    hoursThisWeek: number;
    totalProjects: number;
    completedProjects: number;
}

export default function AppDevDashboard() {
    const [stats, setStats] = useState<DashboardStats>({
        activeProjects: 0,
        activeSprints: 0,
        blockedItems: 0,
        hoursThisWeek: 0,
        totalProjects: 0,
        completedProjects: 0,
    });
    const [loading, setLoading] = useState(true);

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

    const fetchStats = async () => {
        try {
            const projectsRes = await axios.get('/api/app-dev/projects');
            const projects = projectsRes.data;

            setStats({
                activeProjects: projects.filter((p: any) => p.status === 'in_progress').length,
                activeSprints: 0,
                blockedItems: 0,
                hoursThisWeek: 0,
                totalProjects: projects.length,
                completedProjects: projects.filter((p: any) => p.status === 'delivered').length,
            });
        } catch (error) {
            console.error('Error cargando estadísticas:', error);
        } finally {
            setLoading(false);
        }
    };

    const metricCards = [
        {
            icon: '🚀',
            label: 'Proyectos Activos',
            value: stats.activeProjects.toString(),
            gradient: 'linear-gradient(135deg, #667eea, #764ba2)',
            glow: 'rgba(102, 126, 234, 0.4)',
        },
        {
            icon: '⚡',
            label: 'Sprints Activos',
            value: stats.activeSprints.toString(),
            gradient: 'linear-gradient(135deg, #f093fb, #f5576c)',
            glow: 'rgba(240, 147, 251, 0.4)',
        },
        {
            icon: '🚫',
            label: 'Items Bloqueados',
            value: stats.blockedItems.toString(),
            gradient: 'linear-gradient(135deg, #fa709a, #fee140)',
            glow: 'rgba(250, 112, 154, 0.4)',
        },
        {
            icon: '⏱️',
            label: 'Horas Esta Semana',
            value: stats.hoursThisWeek.toFixed(1),
            gradient: 'linear-gradient(135deg, #30cfd0, #330867)',
            glow: 'rgba(48, 207, 208, 0.4)',
        },
    ];

    if (loading) return <div className="p-8 text-center">Cargando dashboard...</div>;

    return (
        <div className="animate-fadeIn">
            <PageHeader
                title="Desarrollo de Aplicaciones"
                subtitle="Gestión ágil de proyectos de software"
                actions={
                    <Link to="/app/app-dev/projects" className="btn btn-primary">
                        🚀 Nuevo Proyecto
                    </Link>
                }
            />

            {/* Metric Cards */}
            <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
                gap: '1.5rem',
                marginBottom: '2rem'
            }}>
                {metricCards.map((card, i) => (
                    <div
                        key={i}
                        className="card"
                        style={{
                            position: 'relative',
                            overflow: 'hidden',
                            boxShadow: `0 8px 32px ${card.glow}`,
                        }}
                    >
                        <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                            <div
                                style={{
                                    width: '60px',
                                    height: '60px',
                                    borderRadius: '50%',
                                    background: card.gradient,
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    fontSize: '1.75rem',
                                    flexShrink: 0,
                                }}
                            >
                                {card.icon}
                            </div>
                            <div style={{ flex: 1 }}>
                                <div style={{
                                    fontSize: '0.875rem',
                                    color: 'var(--text-muted)',
                                    marginBottom: '0.25rem'
                                }}>
                                    {card.label}
                                </div>
                                <div style={{
                                    fontSize: '2rem',
                                    fontWeight: 700,
                                    color: 'var(--text-primary)'
                                }}>
                                    {card.value}
                                </div>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            {/* Quick Actions */}
            <div className="card" style={{ marginBottom: '2rem' }}>
                <h3 style={{ fontSize: '1.25rem', fontWeight: 600, marginBottom: '1rem' }}>
                    🎯 Acciones Rápidas
                </h3>
                <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
                    <Link to="/app/app-dev/projects" className="btn btn-primary">
                        📱 Ver Proyectos
                    </Link>
                    <Link to="/app/app-dev/plans" className="btn btn-ghost">
                        📋 Gestionar Planes
                    </Link>
                    <Link to="/app/app-dev/calendar" className="btn btn-ghost">
                        📅 Ver Calendario
                    </Link>
                </div>
            </div>

            {/* Resumen de Proyectos */}
            <div className="card">
                <h3 style={{ fontSize: '1.25rem', fontWeight: 600, marginBottom: '1rem' }}>
                    📊 Resumen de Proyectos
                </h3>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '1rem' }}>
                    <div>
                        <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)' }}>Total</div>
                        <div style={{ fontSize: '1.5rem', fontWeight: 600 }}>{stats.totalProjects}</div>
                    </div>
                    <div>
                        <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)' }}>En Progreso</div>
                        <div style={{ fontSize: '1.5rem', fontWeight: 600, color: '#3b82f6' }}>
                            {stats.activeProjects}
                        </div>
                    </div>
                    <div>
                        <div style={{ fontSize: '0.875rem', color: 'var(--text-muted)' }}>Completados</div>
                        <div style={{ fontSize: '1.5rem', fontWeight: 600, color: '#10b981' }}>
                            {stats.completedProjects}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
