import { Head, Link } from '@inertiajs/react';
import {
    Users, Clock, Calendar, Building2, UserCheck,
    Globe, FileText, BookOpen, Mail, Bell, Video, LayoutIcon,
} from 'lucide-react';
import {
    BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer,
    PieChart, Pie, Cell, Legend,
} from 'recharts';

// ── Types ────────────────────────────────────────────────────────────────────

interface Stats {
    active_members: number;
    pending_applications: number;
    institutions: number;
    countries: number;
    upcoming_events: number;
    published_posts: number;
    newsletter_subscribers: number;
    unread_messages: number;
    total_users: number;
}

interface TierRow    { name: string; active: number; pending: number }
interface StatusRow  { name: string; value: number }
interface CountryRow { name: string; count: number }
interface ContentRow { label: string; published: number; draft: number }

interface Application {
    id: number; status: string; created_at: string;
    user: { id: number; name: string; email: string };
    tier: { id: number; name: string };
}
interface UpcomingEvent  { id: number; title: string; starts_at: string; location: string | null; type: string }
interface RecentPost     { id: number; title: string; published_at: string; featured_image: string | null }
interface RecentMessage  { id: number; name: string; email: string; subject: string; created_at: string }
interface Subscriber     { id: number; name: string | null; email: string; subscribed_at: string }

interface Props {
    stats: Stats;
    membersByTier: TierRow[];
    subsByStatus: StatusRow[];
    institutionsByCountry: CountryRow[];
    content: ContentRow[];
    recentApplications: Application[];
    upcomingEvents: UpcomingEvent[];
    recentPosts: RecentPost[];
    recentMessages: RecentMessage[];
    recentSubscribers: Subscriber[];
}

// ── Constants ─────────────────────────────────────────────────────────────────

const NAVY   = '#0A2647';
const TEAL   = '#1B6B7D';
const GOLD   = '#D4A843';
const STATUS_COLORS: Record<string, string> = {
    Active: NAVY, Pending: GOLD, Expired: '#6b7280', Cancelled: '#ef4444',
};
const PIE_FALLBACK = ['#0A2647', '#D4A843', '#1B6B7D', '#6b7280', '#ef4444'];

function fmt(dt: string) {
    return new Date(dt).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}
function fmtShort(dt: string) {
    return new Date(dt).toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
}

// ── Sub-components ────────────────────────────────────────────────────────────

function StatCard({ label, value, icon: Icon, href, accent }: {
    label: string; value: number; icon: React.ElementType; href: string; accent: 'navy' | 'teal' | 'gold' | 'red';
}) {
    const styles = {
        navy: { bg: 'bg-[#E5EEF8]', text: 'text-[#0A2647]' },
        teal: { bg: 'bg-[#E0F0F4]', text: 'text-[#1B6B7D]' },
        gold: { bg: 'bg-[#FBF5E0]', text: 'text-[#B8891E]' },
        red:  { bg: 'bg-red-50',    text: 'text-red-600' },
    }[accent];

    return (
        <Link href={href} className="flex items-center gap-4 rounded-xl border border-border bg-card p-5 transition-all hover:shadow-md hover:-translate-y-0.5">
            <div className={`flex h-11 w-11 shrink-0 items-center justify-center rounded-lg ${styles.bg}`}>
                <Icon className={`h-5 w-5 ${styles.text}`} />
            </div>
            <div className="min-w-0">
                <p className="text-2xl font-bold tabular-nums">{value.toLocaleString()}</p>
                <p className="truncate text-xs text-muted-foreground">{label}</p>
            </div>
        </Link>
    );
}

function SectionHeader({ title, href, linkLabel = 'View all' }: { title: string; href?: string; linkLabel?: string }) {
    return (
        <div className="flex items-center justify-between border-b border-border px-6 py-4">
            <h2 className="font-semibold">{title}</h2>
            {href && (
                <Link href={href} className="text-xs text-[#1B6B7D] transition-colors hover:text-[#0A2647]">
                    {linkLabel}
                </Link>
            )}
        </div>
    );
}

// ── Dashboard ─────────────────────────────────────────────────────────────────

export default function AdminDashboard({
    stats, membersByTier, subsByStatus, institutionsByCountry,
    content, recentApplications, upcomingEvents, recentPosts,
    recentMessages, recentSubscribers,
}: Props) {
    return (
        <>
            <Head title="Dashboard" />

            <div className="space-y-6">

                {/* Header */}
                <div>
                    <h1 className="font-serif text-2xl font-bold">Dashboard</h1>
                    <p className="mt-1 text-sm text-muted-foreground">ABEC Africa admin overview</p>
                </div>

                {/* ── Stat cards ── */}
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <StatCard label="Active Members"          value={stats.active_members}          icon={UserCheck}  href="/admin/subscriptions" accent="navy" />
                    <StatCard label="Pending Applications"    value={stats.pending_applications}    icon={Clock}      href="/admin/subscriptions" accent="gold" />
                    <StatCard label="Institutions"            value={stats.institutions}            icon={Building2}  href="/admin/institutions"  accent="navy" />
                    <StatCard label="Countries Represented"   value={stats.countries}               icon={Globe}      href="/admin/institutions"  accent="teal" />
                    <StatCard label="Upcoming Events"         value={stats.upcoming_events}         icon={Calendar}   href="/admin/events"         accent="teal" />
                    <StatCard label="Published Posts"         value={stats.published_posts}         icon={FileText}   href="/admin/posts"          accent="navy" />
                    <StatCard label="Newsletter Subscribers"  value={stats.newsletter_subscribers}  icon={Bell}       href="/admin/newsletter"     accent="teal" />
                    <StatCard label="Unread Messages"         value={stats.unread_messages}         icon={Mail}       href="/admin/messages"        accent={stats.unread_messages > 0 ? 'red' : 'navy'} />
                </div>

                {/* ── Charts row ── */}
                <div className="grid gap-6 lg:grid-cols-3">

                    {/* Members by tier */}
                    <div className="col-span-2 rounded-xl border border-border bg-card">
                        <SectionHeader title="Members by Tier" href="/admin/subscriptions" />
                        <div className="p-6">
                            {membersByTier.length === 0 ? (
                                <p className="py-8 text-center text-sm text-muted-foreground">No subscription data yet.</p>
                            ) : (
                                <ResponsiveContainer width="100%" height={220}>
                                    <BarChart data={membersByTier} barSize={20} barGap={4}>
                                        <XAxis dataKey="name" tick={{ fontSize: 12 }} />
                                        <YAxis allowDecimals={false} tick={{ fontSize: 12 }} width={30} />
                                        <Tooltip />
                                        <Bar dataKey="active"  name="Active"  fill={NAVY} radius={[3, 3, 0, 0]} />
                                        <Bar dataKey="pending" name="Pending" fill={GOLD} radius={[3, 3, 0, 0]} />
                                        <Legend wrapperStyle={{ fontSize: 12 }} />
                                    </BarChart>
                                </ResponsiveContainer>
                            )}
                        </div>
                    </div>

                    {/* Subscriptions by status */}
                    <div className="rounded-xl border border-border bg-card">
                        <SectionHeader title="Subscription Status" />
                        <div className="flex items-center justify-center p-6">
                            {subsByStatus.length === 0 ? (
                                <p className="py-8 text-center text-sm text-muted-foreground">No subscriptions yet.</p>
                            ) : (
                                <ResponsiveContainer width="100%" height={220}>
                                    <PieChart>
                                        <Pie data={subsByStatus} dataKey="value" nameKey="name" cx="50%" cy="50%" innerRadius={55} outerRadius={85} paddingAngle={2}>
                                            {subsByStatus.map((entry, i) => (
                                                <Cell key={entry.name} fill={STATUS_COLORS[entry.name] ?? PIE_FALLBACK[i % PIE_FALLBACK.length]} />
                                            ))}
                                        </Pie>
                                        <Tooltip />
                                        <Legend wrapperStyle={{ fontSize: 12 }} />
                                    </PieChart>
                                </ResponsiveContainer>
                            )}
                        </div>
                    </div>
                </div>

                {/* ── Institutions by country ── */}
                {institutionsByCountry.length > 0 && (
                    <div className="rounded-xl border border-border bg-card">
                        <SectionHeader title="Institutions by Country" href="/admin/institutions" />
                        <div className="p-6">
                            <ResponsiveContainer width="100%" height={200}>
                                <BarChart data={institutionsByCountry} barSize={22} layout="vertical">
                                    <XAxis type="number" allowDecimals={false} tick={{ fontSize: 12 }} />
                                    <YAxis type="category" dataKey="name" width={160} tick={{ fontSize: 12 }} />
                                    <Tooltip />
                                    <Bar dataKey="count" name="Institutions" fill={TEAL} radius={[0, 3, 3, 0]} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </div>
                )}

                {/* ── Content overview + Quick actions ── */}
                <div className="grid gap-6 lg:grid-cols-2">

                    {/* Content counts */}
                    <div className="rounded-xl border border-border bg-card">
                        <SectionHeader title="Content Overview" />
                        <div className="divide-y divide-border">
                            {[
                                { label: 'News Posts',    icon: FileText,   ...content.find(c => c.label === 'Posts')        ?? { published: 0, draft: 0 }, href: '/admin/posts' },
                                { label: 'Publications',  icon: BookOpen,   ...content.find(c => c.label === 'Publications') ?? { published: 0, draft: 0 }, href: '/admin/publications' },
                                { label: 'Events',        icon: Calendar,   ...content.find(c => c.label === 'Events')       ?? { published: 0, draft: 0 }, href: '/admin/events' },
                                { label: 'Videos',        icon: Video,      ...content.find(c => c.label === 'Videos')       ?? { published: 0, draft: 0 }, href: '/admin/videos' },
                                { label: 'Pages',         icon: LayoutIcon, ...content.find(c => c.label === 'Pages')        ?? { published: 0, draft: 0 }, href: '/admin/pages' },
                            ].map(({ label, icon: Icon, published, draft, href }) => (
                                <Link key={label} href={href} className="flex items-center justify-between px-6 py-3.5 transition-colors hover:bg-muted/30">
                                    <div className="flex items-center gap-3">
                                        <Icon className="h-4 w-4 text-muted-foreground" />
                                        <span className="text-sm font-medium">{label}</span>
                                    </div>
                                    <div className="flex items-center gap-3 text-xs">
                                        <span className="rounded-full bg-[#E5EEF8] px-2 py-0.5 font-medium text-[#0A2647]">{published} live</span>
                                        {draft > 0 && <span className="rounded-full bg-muted px-2 py-0.5 text-muted-foreground">{draft} draft</span>}
                                    </div>
                                </Link>
                            ))}
                        </div>
                    </div>

                    {/* Pending applications */}
                    <div className="rounded-xl border border-border bg-card">
                        <SectionHeader title="Pending Applications" href="/admin/subscriptions" />
                        {recentApplications.length === 0 ? (
                            <p className="px-6 py-8 text-center text-sm text-muted-foreground">No pending applications.</p>
                        ) : (
                            <div className="divide-y divide-border">
                                {recentApplications.map((app) => (
                                    <div key={app.id} className="flex items-center justify-between px-6 py-3">
                                        <div className="min-w-0">
                                            <p className="truncate text-sm font-medium">{app.user.name}</p>
                                            <p className="truncate text-xs text-muted-foreground">{app.tier.name} · {fmt(app.created_at)}</p>
                                        </div>
                                        <span className="ml-3 shrink-0 rounded-full bg-yellow-100 px-2.5 py-0.5 text-xs font-medium text-yellow-700">
                                            Pending
                                        </span>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                {/* ── Upcoming events + Recent posts ── */}
                <div className="grid gap-6 lg:grid-cols-2">

                    <div className="rounded-xl border border-border bg-card">
                        <SectionHeader title="Upcoming Events" href="/admin/events" />
                        {upcomingEvents.length === 0 ? (
                            <p className="px-6 py-8 text-center text-sm text-muted-foreground">No upcoming events.</p>
                        ) : (
                            <div className="divide-y divide-border">
                                {upcomingEvents.map((ev) => (
                                    <Link key={ev.id} href={`/admin/events/${ev.id}/edit`} className="flex items-center gap-4 px-6 py-3.5 transition-colors hover:bg-muted/30">
                                        <div className="flex h-10 w-10 shrink-0 flex-col items-center justify-center rounded-lg bg-[#E0F0F4] text-[#1B6B7D]">
                                            <span className="text-[10px] font-bold uppercase leading-none">{new Date(ev.starts_at).toLocaleDateString('en-GB', { month: 'short' })}</span>
                                            <span className="text-lg font-bold leading-none">{new Date(ev.starts_at).getDate()}</span>
                                        </div>
                                        <div className="min-w-0">
                                            <p className="truncate text-sm font-medium">{ev.title}</p>
                                            <p className="truncate text-xs text-muted-foreground">{ev.location ?? 'Online'} · {ev.type}</p>
                                        </div>
                                    </Link>
                                ))}
                            </div>
                        )}
                    </div>

                    <div className="rounded-xl border border-border bg-card">
                        <SectionHeader title="Recent News" href="/admin/posts" linkLabel="All posts" />
                        {recentPosts.length === 0 ? (
                            <p className="px-6 py-8 text-center text-sm text-muted-foreground">No published posts yet.</p>
                        ) : (
                            <div className="divide-y divide-border">
                                {recentPosts.map((post) => (
                                    <Link key={post.id} href={`/admin/posts/${post.id}/edit`} className="flex items-center gap-4 px-6 py-3.5 transition-colors hover:bg-muted/30">
                                        {post.featured_image ? (
                                            <img src={post.featured_image} alt="" className="h-10 w-10 shrink-0 rounded-md object-cover" />
                                        ) : (
                                            <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-muted">
                                                <FileText className="h-4 w-4 text-muted-foreground" />
                                            </div>
                                        )}
                                        <div className="min-w-0">
                                            <p className="truncate text-sm font-medium">{post.title}</p>
                                            <p className="text-xs text-muted-foreground">{fmtShort(post.published_at)}</p>
                                        </div>
                                    </Link>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

                {/* ── Messages + Newsletter ── */}
                <div className="grid gap-6 lg:grid-cols-2">

                    <div className="rounded-xl border border-border bg-card">
                        <SectionHeader title="Unread Messages" href="/admin/messages" />
                        {recentMessages.length === 0 ? (
                            <p className="px-6 py-8 text-center text-sm text-muted-foreground">Inbox is clear.</p>
                        ) : (
                            <div className="divide-y divide-border">
                                {recentMessages.map((msg) => (
                                    <Link key={msg.id} href={`/admin/messages/${msg.id}`} className="flex items-start gap-4 px-6 py-3.5 transition-colors hover:bg-muted/30">
                                        <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-red-50 text-red-600">
                                            <Mail className="h-3.5 w-3.5" />
                                        </div>
                                        <div className="min-w-0">
                                            <p className="truncate text-sm font-medium">{msg.subject}</p>
                                            <p className="truncate text-xs text-muted-foreground">{msg.name} · {fmt(msg.created_at)}</p>
                                        </div>
                                    </Link>
                                ))}
                            </div>
                        )}
                    </div>

                    <div className="rounded-xl border border-border bg-card">
                        <SectionHeader title="Recent Subscribers" href="/admin/newsletter" />
                        {recentSubscribers.length === 0 ? (
                            <p className="px-6 py-8 text-center text-sm text-muted-foreground">No subscribers yet.</p>
                        ) : (
                            <div className="divide-y divide-border">
                                {recentSubscribers.map((sub) => (
                                    <div key={sub.id} className="flex items-center gap-4 px-6 py-3.5">
                                        <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-[#E0F0F4] text-xs font-bold text-[#1B6B7D]">
                                            {(sub.name ?? sub.email)[0].toUpperCase()}
                                        </div>
                                        <div className="min-w-0">
                                            <p className="truncate text-sm font-medium">{sub.name ?? sub.email}</p>
                                            {sub.name && <p className="truncate text-xs text-muted-foreground">{sub.email}</p>}
                                        </div>
                                        <span className="ml-auto shrink-0 text-xs text-muted-foreground">{fmtShort(sub.subscribed_at)}</span>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>

            </div>
        </>
    );
}
