const { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } = window.Recharts || {};

function StatCard({ label, value, colorClass, icon }) {
    const { useState, useEffect } = window.React;
    return (
        <div className={`stat-card ${colorClass || ''}`}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <p className="stat-card-label">{label}</p>
                <span style={{ fontSize: '1.25rem' }}>{icon}</span>
            </div>
            <p className={`stat-card-value ${colorClass || ''}`}>{value ?? '—'}</p>
        </div>
    );
}

const CustomTooltip = ({ active, payload, label }) => {
    if (active && payload && payload.length) {
        return (
            <div style={{
                background: 'var(--surface-2)', border: '1px solid var(--border)',
                borderRadius: '6px', padding: '10px 14px', fontFamily: 'var(--font-body)'
            }}>
                <p style={{ color: 'var(--text-secondary)', fontSize: '0.75rem' }}>{label}</p>
                <p style={{ color: 'var(--accent)', fontWeight: 700, fontSize: '1.1rem' }}>
                    {payload[0].value} veículos
                </p>
            </div>
        );
    }
    return null;
};

function Dashboard() {
    const { useState, useEffect } = window.React;
    const [stats, setStats] = useState(null);
    const [notifications, setNotifications] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        Promise.all([
            window.api.getDashboardStats(),
            window.api.getNotifications()
        ]).then(([statsData, notifData]) => {
            setStats(statsData);
            setNotifications(notifData);
            setLoading(false);
        }).catch(() => setLoading(false));
    }, []);

    if (loading) return (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '50vh', color: 'var(--text-secondary)' }}>
            Carregando métricas...
        </div>
    );

    if (!stats) return (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '50vh', color: 'var(--red)' }}>
            Erro ao carregar. Verifique se o backend está rodando.
        </div>
    );

    const kpis = stats.kpis;
    const chartData = stats.weekly_distribution || [];
    const topServices = stats.top_services || [];
    const mechanicProd = stats.mechanic_productivity || [];

    const missingComponents = [];
    if (!window.Recharts) missingComponents.push('window.Recharts');
    else {
        if (!AreaChart) missingComponents.push('AreaChart');
        if (!Area) missingComponents.push('Area');
        if (!XAxis) missingComponents.push('XAxis');
        if (!YAxis) missingComponents.push('YAxis');
        if (!CartesianGrid) missingComponents.push('CartesianGrid');
        if (!Tooltip) missingComponents.push('Tooltip');
        if (!ResponsiveContainer) missingComponents.push('ResponsiveContainer');
    }

    return (
        <div>
            <header className="page-header">
                <div>
                    <h1>DASHBOARD</h1>
                    <p className="text-secondary text-sm" style={{ marginTop: '4px' }}>
                        Visão geral da operação da Machado Car Service
                    </p>
                </div>
                <div style={{
                    padding: '8px 14px', background: 'var(--surface)', border: '1px solid var(--border)',
                    borderRadius: 'var(--radius)', fontSize: '0.75rem', color: 'var(--text-muted)',
                    fontFamily: 'var(--font-mono)'
                }}>
                    {new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: '2-digit', month: 'long' })}
                </div>
            </header>

            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '20px', marginBottom: '32px' }}>
                <StatCard label="Total Ativos" value={kpis.total_active} icon="🔧" />
                <StatCard label="Em Execução" value={kpis.in_progress} colorClass="highlight" icon="⚡" />
                <StatCard label="Aguardando Peça" value={kpis.waiting_parts}
                    colorClass={kpis.waiting_parts > 0 ? 'red' : ''} icon="📦" />
                <StatCard label="Concluídos" value={kpis.completed_today} colorClass="green" icon="✅" />
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: '20px' }}>
                <div className="card">
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
                        <div>
                            <h3 style={{ margin: 0 }}>Fluxo Semanal de Atendimentos</h3>
                            <p className="text-secondary text-sm" style={{ marginTop: '4px' }}>
                                Veículos atendidos por dia na semana
                            </p>
                        </div>
                        <div style={{
                            padding: '6px 12px', background: 'var(--accent-glow)', border: '1px solid var(--accent-dim)',
                            borderRadius: '20px', fontSize: '0.75rem', fontWeight: 600, color: 'var(--accent)'
                        }}>
                            Eficiência Operacional: {kpis.efficiency}
                        </div>
                    </div>

                    {missingComponents.length > 0 ? (
                        <div style={{ padding: '20px', background: 'var(--red)', color: 'white', fontWeight: 'bold' }}>
                            RECHARTS ESTÁ FALTANDO: {missingComponents.join(', ')}
                        </div>
                    ) : chartData.length > 0 ? (
                        <ResponsiveContainer width="100%" height={280}>
                            <AreaChart data={chartData} margin={{ top: 4, right: 4, left: -20, bottom: 0 }}>
                                <defs>
                                    <linearGradient id="colorAtend" x1="0" y1="0" x2="0" y2="1">
                                        <stop offset="5%"  stopColor="#f0a500" stopOpacity={0.3} />
                                        <stop offset="95%" stopColor="#f0a500" stopOpacity={0} />
                                    </linearGradient>
                                </defs>
                                <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" vertical={false} />
                                <XAxis dataKey="name" tick={{ fill: 'var(--text-muted)', fontSize: 12 }} axisLine={false} tickLine={false} />
                                <YAxis tick={{ fill: 'var(--text-muted)', fontSize: 12 }} axisLine={false} tickLine={false} allowDecimals={false} />
                                <Tooltip content={<CustomTooltip />} />
                                <Area
                                    type="monotone" dataKey="atendimentos"
                                    stroke="var(--accent)" strokeWidth={2}
                                    fill="url(#colorAtend)" dot={{ fill: 'var(--accent)', r: 4, strokeWidth: 0 }}
                                    activeDot={{ r: 6, fill: 'var(--accent-hover)', strokeWidth: 0 }}
                                />
                            </AreaChart>
                        </ResponsiveContainer>
                    ) : (
                        <div className="empty-state">
                            <p className="text-secondary text-sm">Sem dados de fluxo disponíveis.</p>
                        </div>
                    )}
                </div>

                <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
                    <div className="card">
                        <h3 style={{ margin: '0 0 16px 0', fontSize: '1.1rem' }}>Alertas da Oficina</h3>
                        {notifications.length === 0 ? (
                            <p className="text-secondary text-sm">Tudo tranquilo! Nenhum alerta no momento.</p>
                        ) : (
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                                {notifications.map(n => (
                                    <div key={n.id} style={{
                                        padding: '10px 12px', borderRadius: '6px', fontSize: '0.875rem',
                                        background: n.type === 'error' ? 'var(--red-glow)' : 'var(--surface-2)',
                                        borderLeft: `4px solid ${n.type === 'error' ? 'var(--red)' : 'var(--orange)'}`
                                    }}>
                                        <strong style={{ display: 'block', color: n.type === 'error' ? 'var(--red)' : 'var(--orange)', marginBottom: '4px' }}>
                                            {n.type === 'error' ? 'Urgente' : 'Aviso'}
                                        </strong>
                                        {n.message}
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>

                    <div className="card">
                        <h3 style={{ margin: '0 0 16px 0', fontSize: '1.1rem' }}>Métricas Avançadas</h3>
                        <div style={{ marginBottom: '16px' }}>
                            <p className="input-label" style={{ marginBottom: '4px' }}>Tempo Médio de Serviço</p>
                            <p style={{ fontSize: '1.25rem', fontWeight: 'bold' }}>{kpis.avg_service_time_hours} Horas</p>
                        </div>
                        <hr style={{ border: 'none', borderTop: '1px solid var(--border)', margin: '16px 0' }} />
                        <div style={{ marginBottom: '16px' }}>
                            <p className="input-label" style={{ marginBottom: '8px' }}>Serviços Mais Realizados</p>
                            {topServices.length ? topServices.map((ts, i) => (
                                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.875rem', marginBottom: '4px' }}>
                                    <span>{ts.name}</span>
                                    <strong style={{ color: 'var(--accent)' }}>{ts.count}</strong>
                                </div>
                            )) : <p className="text-secondary text-sm">Sem dados</p>}
                        </div>
                        <hr style={{ border: 'none', borderTop: '1px solid var(--border)', margin: '16px 0' }} />
                        <div>
                            <p className="input-label" style={{ marginBottom: '8px' }}>Produtividade (Concluídos)</p>
                            {mechanicProd.length ? mechanicProd.map((mp, i) => (
                                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.875rem', marginBottom: '4px' }}>
                                    <span>{mp.name}</span>
                                    <strong>{mp.completed}</strong>
                                </div>
                            )) : <p className="text-secondary text-sm">Sem mecânicos</p>}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

window.Dashboard = Dashboard;
