import React, { useState, useEffect, useCallback } from 'react';
import { useAdmin } from '../../context/AdminContext';

const STATUS_COLORS = {
    active:    { bg: '#dcfce7', color: '#166534' },
    launched:  { bg: '#dcfce7', color: '#166534' },
    staged:    { bg: '#dbeafe', color: '#1e40af' },
    draft:     { bg: '#f1f5f9', color: '#475569' },
    paused:    { bg: '#fef9c3', color: '#854d0e' },
    completed: { bg: '#ede9fe', color: '#5b21b6' },
    cancelled: { bg: '#fee2e2', color: '#991b1b' },
};

const fmtCurrency = (n) => n != null ? `$${Number(n).toLocaleString('en-US', { minimumFractionDigits: 2 })}` : '—';
const fmtNum     = (n) => n != null ? Number(n).toLocaleString() : '—';
const fmtDate    = (d) => d ? new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '—';

function StatusBadge({ status }) {
    const s = STATUS_COLORS[status?.toLowerCase()] || { bg: '#f1f5f9', color: '#475569' };
    return (
        <span style={{ background: s.bg, color: s.color, padding: '2px 8px', borderRadius: 10, fontSize: 11, fontWeight: 600 }}>
            {status || '—'}
        </span>
    );
}

function StatCard({ label, value, sub }) {
    return (
        <div style={{
            background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10,
            padding: '20px 24px', flex: '1 1 180px',
        }}>
            <div style={{ fontSize: 28, fontWeight: 700, color: '#0f172a' }}>{value}</div>
            <div style={{ fontSize: 13, color: '#64748b', marginTop: 4 }}>{label}</div>
            {sub && <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 2 }}>{sub}</div>}
        </div>
    );
}

export default function OverviewPanel() {
    const { apiCall, clientId, clientName, setActiveCategory, setActiveTab } = useAdmin();
    const [initiatives, setInitiatives] = useState([]);
    const [recommendations, setRecommendations] = useState([]);
    const [loading, setLoading] = useState(true);

    const load = useCallback(async () => {
        setLoading(true);
        const [iRes, rRes] = await Promise.all([
            apiCall('/api/initiative'),
            apiCall('/api/recommendations'),
        ]);
        setInitiatives(Array.isArray(iRes?.initiatives) ? iRes.initiatives :
                       Array.isArray(iRes?.data) ? iRes.data : []);
        setRecommendations(Array.isArray(rRes?.recommendations) ? rRes.recommendations :
                           Array.isArray(rRes?.data) ? rRes.data : []);
        setLoading(false);
    }, [apiCall]);

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

    const active    = initiatives.filter(i => ['active','launched'].includes(i.iniStatus?.toLowerCase() || i.status?.toLowerCase()));
    const staged    = initiatives.filter(i => ['staged','draft'].includes(i.iniStatus?.toLowerCase() || i.status?.toLowerCase()));
    const critical  = recommendations.filter(r => r.severity === 'critical' || r.Severity === 'critical');

    const totalSpend = active.reduce((sum, i) => sum + (i.totalSpend || 0), 0);

    if (loading) return <div className="loading-message">Loading your dashboard…</div>;

    return (
        <div style={{ maxWidth: 960 }}>
            {/* Welcome */}
            <div style={{ marginBottom: 24 }}>
                <h2 style={{ fontSize: 22, fontWeight: 700, color: '#0f172a', margin: 0 }}>
                    Welcome back{clientName ? `, ${clientName}` : ''}
                </h2>
                <p style={{ color: '#64748b', margin: '4px 0 0' }}>
                    Here's a summary of your advertising activity.
                </p>
            </div>

            {/* Stats row */}
            <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', marginBottom: 28 }}>
                <StatCard label="Active Campaigns"  value={active.length}  />
                <StatCard label="Drafts / Staged"   value={staged.length}  />
                <StatCard label="Open Alerts"        value={critical.length} sub={critical.length > 0 ? 'Needs attention' : 'All clear'} />
                <StatCard label="Total Spend (MTD)"  value={totalSpend > 0 ? fmtCurrency(totalSpend) : '—'} />
            </div>

            {/* Active campaigns */}
            {active.length > 0 && (
                <div style={{ marginBottom: 28 }}>
                    <h3 style={{ fontSize: 15, fontWeight: 600, color: '#0f172a', marginBottom: 12 }}>
                        Active Campaigns
                    </h3>
                    <div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 10, overflow: 'hidden' }}>
                        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                            <thead>
                                <tr style={{ background: '#f8fafc' }}>
                                    <th style={{ padding: '10px 16px', textAlign: 'left', color: '#64748b', fontWeight: 600 }}>Campaign</th>
                                    <th style={{ padding: '10px 16px', textAlign: 'left', color: '#64748b', fontWeight: 600 }}>Status</th>
                                    <th style={{ padding: '10px 16px', textAlign: 'right', color: '#64748b', fontWeight: 600 }}>Budget</th>
                                    <th style={{ padding: '10px 16px', textAlign: 'left', color: '#64748b', fontWeight: 600 }}>Ends</th>
                                </tr>
                            </thead>
                            <tbody>
                                {active.slice(0, 5).map((ini, idx) => (
                                    <tr key={ini.iniId || ini.initiativeId || idx}
                                        style={{ borderTop: '1px solid #f1f5f9', cursor: 'pointer' }}
                                        onClick={() => { setActiveCategory('campaigns'); setActiveTab('myCampaigns'); }}
                                    >
                                        <td style={{ padding: '12px 16px', fontWeight: 500, color: '#0f172a' }}>
                                            {ini.iniName || ini.name || '—'}
                                        </td>
                                        <td style={{ padding: '12px 16px' }}>
                                            <StatusBadge status={ini.iniStatus || ini.status} />
                                        </td>
                                        <td style={{ padding: '12px 16px', textAlign: 'right', color: '#475569' }}>
                                            {fmtCurrency(ini.iniTotalBudget || ini.totalBudget)}
                                        </td>
                                        <td style={{ padding: '12px 16px', color: '#64748b' }}>
                                            {fmtDate(ini.iniEndDate || ini.endDate)}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                    {active.length > 5 && (
                        <button
                            style={{ marginTop: 8, fontSize: 13, color: 'var(--accent)', background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}
                            onClick={() => { setActiveCategory('campaigns'); setActiveTab('myCampaigns'); }}
                        >
                            View all {active.length} campaigns →
                        </button>
                    )}
                </div>
            )}

            {/* Recommendations */}
            {recommendations.length > 0 && (
                <div>
                    <h3 style={{ fontSize: 15, fontWeight: 600, color: '#0f172a', marginBottom: 12 }}>
                        Recommendations
                    </h3>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                        {recommendations.slice(0, 3).map((r, idx) => {
                            const sev = r.severity || r.Severity || 'info';
                            const border = sev === 'critical' ? '#fca5a5' : sev === 'warning' ? '#fcd34d' : '#93c5fd';
                            return (
                                <div key={r.recommendationId || r.RecId || idx} style={{
                                    background: '#fff', border: `1px solid ${border}`,
                                    borderRadius: 8, padding: '14px 16px',
                                }}>
                                    <div style={{ fontWeight: 600, fontSize: 13, color: '#0f172a' }}>
                                        {r.title || r.Title || 'Recommendation'}
                                    </div>
                                    <div style={{ fontSize: 12, color: '#64748b', marginTop: 4 }}>
                                        {r.recommendation || r.Recommendation || r.description || r.Description}
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {initiatives.length === 0 && recommendations.length === 0 && (
                <div style={{ textAlign: 'center', padding: '60px 20px', color: '#94a3b8' }}>
                    <div style={{ fontSize: 40, marginBottom: 12 }}>📣</div>
                    <div style={{ fontSize: 16, fontWeight: 600, color: '#475569', marginBottom: 8 }}>
                        No campaigns yet
                    </div>
                    <div style={{ marginBottom: 20 }}>Create your first campaign to start advertising on Google, Meta, and TikTok.</div>
                    <button
                        className="btn-action"
                        onClick={() => { setActiveCategory('campaigns'); setActiveTab('newCampaign'); }}
                    >
                        Create Campaign
                    </button>
                </div>
            )}
        </div>
    );
}
