import { useEffect, useState } from '@wordpress/element';
import { ShieldCheckIcon, BellAlertIcon, ChartBarIcon, DevicePhoneMobileIcon, CubeIcon, ArrowPathIcon } from '@heroicons/react/20/solid';
import Layout from '../layout/Layout';
import { getAnalyticsOverview } from '../../api/local';

const highlights = [
    {
        name: 'Custom JWT Payloads',
        description: 'Pick username, email, roles, profile, ACF, and WooCommerce meta fields directly from the settings UI.',
        icon: CubeIcon,
    },
    {
        name: 'Real-time Security Webhooks',
        description: 'Notify mobile apps and external dashboards about logins, refreshes, brute-force events, and blocked IPs.',
        icon: BellAlertIcon,
    },
    {
        name: 'Login Heatmap & Analytics',
        description: 'Track peak activity hours, location clusters, and traffic spikes without installing a Pro add-on.',
        icon: ChartBarIcon,
    },
    {
        name: 'Multi-Token Sessions',
        description: 'Allow or limit simultaneous devices, force-expire stale tokens, and monitor everything from Live Monitor.',
        icon: DevicePhoneMobileIcon,
    },
    {
        name: 'Security-first Defaults',
        description: 'Brute-force guard, IP controls, secret generation, and webhook signatures ship in the free version.',
        icon: ShieldCheckIcon,
    },
    {
        name: 'Plugin-level SSO',
        description: 'Connect multiple WordPress installs with shared secrets so users roam between sites without relogging.',
        icon: ArrowPathIcon,
    },
];

const Dashboard = () => {
    const [analytics, setAnalytics] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        let mounted = true;
        const fetchAnalytics = async () => {
            try {
                const data = await getAnalyticsOverview();
                if (mounted) {
                    setAnalytics(data);
                }
            } catch (error) {
                console.error('Analytics fetch failed', error);
            } finally {
                if (mounted) {
                    setLoading(false);
                }
            }
        };
        fetchAnalytics();
        return () => {
            mounted = false;
        };
    }, []);

    const summary = analytics?.summary || {};
    const topUsers = analytics?.top_users || [];
    const heatmap = analytics?.failed_heatmap?.slice(0, 12) || [];
    const locations = analytics?.locations?.slice(0, 6) || [];
    const devices = analytics?.devices?.slice(0, 6) || [];
    const spike = analytics?.spike;

    return (
        <Layout>
            <div className="space-y-8">
                <section className="bg-white rounded-lg p-8">
                    <p className="text-sm font-semibold text-gray-600 uppercase">HeadlessKey – JWT Auth Dashboard</p>
                    <h1 className="mt-2 text-3xl font-bold text-gray-900">Enterprise-grade JWT auth without a paywall</h1>
                    <p className="mt-3 text-gray-600 text-lg">
                        Monitor tokens in real time, trigger security webhooks, and share single sign-on sessions across any WordPress stack.
                    </p>
                </section>

                <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                    {['active', 'revoked', 'expired', 'last_hour'].map((key) => (
                        <div key={key} className="bg-white rounded-lg p-4 shadow-sm border border-gray-100">
                            <p className="text-sm text-gray-500 uppercase">{key.replace('_', ' ')}</p>
                            <p className="mt-2 text-3xl font-bold text-gray-900">{summary[key] ?? (loading ? '…' : 0)}</p>
                        </div>
                    ))}
                    {!loading && spike && (
                        <div className={`bg-white rounded-lg p-4 shadow-sm border ${spike.detected ? 'border-amber-400' : 'border-gray-100'}`}>
                            <p className="text-sm text-gray-500 uppercase">Traffic Spike</p>
                            <p className="mt-2 text-xl font-semibold text-gray-900">{spike.detected ? 'Heads up!' : 'Stable'}</p>
                            <p className="text-sm text-gray-600 mt-1">
                                Last hour: {spike.last_hour} requests (avg {spike.average_per_hour} / hr)
                            </p>
                        </div>
                    )}
                </section>

                <section className="grid gap-6 lg:grid-cols-2">
                    <div className="bg-white rounded-lg p-6">
                        <h2 className="text-lg font-semibold text-gray-900">Most active users</h2>
                        <p className="text-sm text-gray-500">Keep an eye on who issues the most tokens.</p>
                        <div className="mt-4 overflow-x-auto">
                            <table className="min-w-full text-sm">
                                <thead>
                                    <tr className="text-left text-xs uppercase text-gray-500">
                                        <th className="py-2">User ID</th>
                                        <th className="py-2">Tokens</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {(loading ? [] : topUsers).map((user) => (
                                        <tr key={user.user_id} className="border-t border-gray-100">
                                            <td className="py-2 font-medium text-gray-900">#{user.user_id}</td>
                                            <td className="py-2 text-gray-600">{user.total}</td>
                                        </tr>
                                    ))}
                                    {!loading && topUsers.length === 0 && (
                                        <tr>
                                            <td className="py-4 text-gray-500" colSpan="2">No activity yet.</td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div className="bg-white rounded-lg p-6">
                        <h2 className="text-lg font-semibold text-gray-900">Failed login heatmap</h2>
                        <p className="text-sm text-gray-500">Latest hot spots from the past few days.</p>
                        <div className="mt-4 grid gap-3 sm:grid-cols-2">
                            {(loading ? [] : heatmap).map((item, idx) => (
                                <div key={idx} className="rounded-md border border-gray-100 p-3">
                                    <p className="text-sm font-medium text-gray-900">{item.day}</p>
                                    <p className="text-xs text-gray-500">Hour {item.hour}:00</p>
                                    <p className="mt-1 text-lg font-semibold text-gray-900">{item.total} attempts</p>
                                </div>
                            ))}
                            {!loading && heatmap.length === 0 && (
                                <p className="text-sm text-gray-500">No failed logins recorded yet.</p>
                            )}
                        </div>
                    </div>
                </section>

                <section className="grid gap-6 lg:grid-cols-2">
                    <div className="bg-white rounded-lg p-6">
                        <h2 className="text-lg font-semibold text-gray-900">Top locations</h2>
                        <ul className="mt-4 space-y-2 text-sm text-gray-600">
                            {(loading ? [] : locations).map((entry, idx) => (
                                <li key={idx} className="flex items-center justify-between border-b border-gray-100 pb-2">
                                    <span>{entry.ip_address || 'N/A'}</span>
                                    <span className="font-semibold text-gray-900">{entry.total}</span>
                                </li>
                            ))}
                            {!loading && locations.length === 0 && <li className="text-gray-500">No IP data yet.</li>}
                        </ul>
                    </div>
                    <div className="bg-white rounded-lg p-6">
                        <h2 className="text-lg font-semibold text-gray-900">Devices in use</h2>
                        <ul className="mt-4 space-y-2 text-sm text-gray-600">
                            {(loading ? [] : devices).map((entry, idx) => (
                                <li key={idx} className="flex items-center justify-between border-b border-gray-100 pb-2">
                                    <span className="truncate">{entry.device || 'Unknown device'}</span>
                                    <span className="font-semibold text-gray-900">{entry.total}</span>
                                </li>
                            ))}
                            {!loading && devices.length === 0 && <li className="text-gray-500">No device fingerprints captured yet.</li>}
                        </ul>
                    </div>
                </section>

                <section className="bg-white rounded-lg p-6">
                    <h2 className="text-lg font-semibold text-gray-900">Premium-grade features (free)</h2>
                    <div className="mt-6 grid gap-6 md:grid-cols-2 xl:grid-cols-3">
                        {highlights.map((feature) => (
                            <div key={feature.name} className="flex gap-4">
                                <feature.icon className="h-8 w-8 text-gray-700" />
                                <div>
                                    <h3 className="text-base font-semibold text-gray-900">{feature.name}</h3>
                                    <p className="text-sm text-gray-600">{feature.description}</p>
                                </div>
                            </div>
                        ))}
                    </div>
                </section>
            </div>
        </Layout>
    );
};

export default Dashboard;