import type { Metadata } from "next";
import Link from "next/link";
import { BookOpen, Briefcase, CreditCard, Bell, PenLine, ArrowRight, CheckCircle, Clock, User, AlertCircle, Package, ExternalLink } from "lucide-react";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { redirect } from "next/navigation";

export const metadata: Metadata = { title: "Dashboard" };

export default async function DashboardPage() {
  const session = await auth();
  if (!session?.user?.id) redirect("/login");

  const user = await db.user.findUnique({
    where: { id: session.user.id },
    include: {
      subscriptions: {
        where: { status: "active" },
        include: { package: true },
        orderBy: { createdAt: "desc" },
      },
      journals: {
        orderBy: { createdAt: "desc" },
        take: 3,
        select: { id: true, title: true, slug: true, status: true, createdAt: true },
      },
      jobApplications: {
        orderBy: { createdAt: "desc" },
        take: 5,
        select: { id: true, status: true, createdAt: true, job: { select: { title: true, company: true } } },
      },
      orders: {
        orderBy: { createdAt: "desc" },
        take: 5,
        include: {
          items: {
            include: { product: { select: { name: true, slug: true } } },
          },
        },
      },
    },
  });

  if (!user) redirect("/login");

  const activeSubscription = user.subscriptions[0] ?? null;
  
  // Check if user has active academician subscription
  const hasAcademicianModule = user.role === "admin" || 
    user.subscriptions.some(sub => sub.status === "active" && sub.package.module === "academician");
  
  // Check if user has active job_seeker subscription
  const hasJobSeekerModule = user.role === "admin" || 
    user.subscriptions.some(sub => sub.status === "active" && sub.package.module === "job_seeker");
  
  const isJournalSubscriber = hasAcademicianModule;
  const isJobSeeker = hasJobSeekerModule;

  const roleBadge: Record<string, string> = {
    admin: "Admin",
    journal_subscriber: "Journal Subscriber",
    job_seeker: "Job Seeker",
    registered: "Free Account",
    guest: "Guest",
  };

  return (
    <div className="min-h-screen bg-neutral-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-2xl font-bold text-navy-800">Welcome back, {user.name.split(" ")[0]}</h1>
            <p className="text-neutral-500 text-sm mt-0.5">
              {roleBadge[user.role] ?? user.role}
              {activeSubscription?.currentPeriodEnd &&
                ` · Renews ${new Date(activeSubscription.currentPeriodEnd).toLocaleDateString("en-MY", { day: "numeric", month: "short", year: "numeric" })}`}
            </p>
          </div>
          <div className="flex items-center gap-3">
            <Link
              href="/dashboard/profile"
              className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-navy-700 border border-navy-200 rounded-lg hover:bg-navy-50 transition-colors"
            >
              <User size={14} /> My Profile
            </Link>
            {!isJobSeeker && (
              <Link
                href="/register?plan=job_seeker"
                className="px-4 py-2 bg-gold-500 text-white text-sm font-semibold rounded-lg hover:bg-gold-600 transition-colors"
              >
                Upgrade to Job Seeker
              </Link>
            )}
          </div>
        </div>

        {/* Email verification banner */}
        {!user.emailVerified && (
          <div className="mb-6 flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-xl">
            <AlertCircle size={18} className="text-amber-600 shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="text-sm font-medium text-amber-800">Please verify your email address</p>
              <p className="text-xs text-amber-700 mt-0.5">
                Check your inbox for a verification link. Some features may be limited until verified.
              </p>
            </div>
          </div>
        )}

        {/* Subscription card */}
        {activeSubscription ? (
          <div className="bg-navy-700 rounded-2xl p-6 text-white mb-8">
            <div className="flex items-center justify-between mb-4">
              <div>
                <div className="text-xs text-navy-300 uppercase tracking-wider mb-1">Current Plan</div>
                <div className="text-xl font-bold">{activeSubscription.package.name}</div>
              </div>
              <div className="text-right">
                <div className="text-xs text-navy-300 mb-1">
                  {activeSubscription.package.billingPeriod === "monthly" ? "Monthly" : "Annual"}
                </div>
                <div className="text-2xl font-bold">
                  {activeSubscription.currency === "ngn"
                    ? `₦${Number(activeSubscription.package.priceNgn).toLocaleString()}`
                    : `$${Number(activeSubscription.package.priceUsd).toFixed(0)}`}
                </div>
              </div>
            </div>
            <div className="flex items-center gap-4 text-sm text-navy-200">
              {isJournalSubscriber && (
                <div className="flex items-center gap-1.5">
                  <CheckCircle size={14} className="text-emerald-400" /> Journals
                </div>
              )}
              {isJobSeeker && (
                <div className="flex items-center gap-1.5">
                  <CheckCircle size={14} className="text-emerald-400" /> Jobs Apply
                </div>
              )}
              {!isJournalSubscriber && (
                <div className="flex items-center gap-1.5 opacity-50">
                  <Clock size={14} /> Journals
                </div>
              )}
            </div>
            {activeSubscription.currentPeriodEnd && (
              <div className="text-xs text-navy-300 mt-3">
                Renews{" "}
                {new Date(activeSubscription.currentPeriodEnd).toLocaleDateString("en-MY", {
                  day: "numeric",
                  month: "long",
                  year: "numeric",
                })}
              </div>
            )}
          </div>
        ) : (
          <div className="bg-neutral-800 rounded-2xl p-6 text-white mb-8 flex items-center justify-between">
            <div>
              <div className="text-xs text-neutral-400 uppercase tracking-wider mb-1">Current Plan</div>
              <div className="text-xl font-bold">Free Account</div>
              <p className="text-sm text-neutral-400 mt-1">Upgrade to access journals, job applications and more.</p>
            </div>
            <Link
              href="/register?plan=journal_subscriber"
              className="px-5 py-2.5 bg-gold-500 hover:bg-gold-400 text-navy-900 font-semibold text-sm rounded-xl transition-colors"
            >
              Browse Plans
            </Link>
          </div>
        )}

        {/* Quick stats */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
          {[
            ...(isJournalSubscriber ? [{ label: "My Journals", value: String(user.journals.length), icon: BookOpen, color: "bg-blue-50 text-blue-600" }] : []),
            ...(isJobSeeker ? [{ label: "Applications", value: String(user.jobApplications.length), icon: Briefcase, color: "bg-amber-50 text-amber-600" }] : []),
            { label: "Orders", value: String(user.orders.length), icon: Package, color: "bg-emerald-50 text-emerald-600" },
            { label: "Active Plans", value: String(user.subscriptions.length), icon: CreditCard, color: "bg-purple-50 text-purple-600" },
          ].map(({ label, value, icon: Icon, color }) => (
            <div key={label} className="bg-white rounded-xl border border-neutral-200 p-5">
              <div className={`inline-flex items-center justify-center w-10 h-10 rounded-xl mb-3 ${color}`}>
                <Icon size={18} />
              </div>
              <div className="text-2xl font-bold text-navy-800">{value}</div>
              <div className="text-sm text-neutral-500 mt-0.5">{label}</div>
            </div>
          ))}
        </div>

        <div className="grid lg:grid-cols-2 gap-6">
          {/* My Orders */}
          <div className="bg-white rounded-2xl border border-neutral-200 p-6">
            <div className="flex items-center justify-between mb-5">
              <h2 className="font-semibold text-navy-800">My Orders</h2>
              <Link href="/shop" className="flex items-center gap-1 text-xs font-medium text-navy-700 hover:text-navy-900">
                Browse Shop <ArrowRight size={12} />
              </Link>
            </div>
            {user.orders.length > 0 ? (
              <div className="space-y-3">
                {user.orders.map((order) => (
                  <Link
                    key={order.id}
                    href={`/dashboard/orders/${order.id}`}
                    className="flex items-center justify-between p-3 rounded-xl hover:bg-neutral-50 transition-colors"
                  >
                    <div className="flex-1 min-w-0 mr-4">
                      <div className="text-sm font-medium text-neutral-800">
                        Order #{order.id.slice(-8).toUpperCase()}
                      </div>
                      <div className="text-xs text-neutral-400 mt-0.5">
                        {order.items.length} item{order.items.length > 1 ? "s" : ""} · ${Number(order.total).toFixed(2)}
                      </div>
                    </div>
                    <span className={`text-xs font-medium px-2.5 py-1 rounded-full shrink-0 ${
                      order.status === "completed" ? "bg-emerald-50 text-emerald-700" :
                      order.status === "shipped" ? "bg-blue-50 text-blue-700" :
                      order.status === "paid" ? "bg-purple-50 text-purple-700" :
                      order.status === "cancelled" || order.status === "refunded" ? "bg-red-50 text-red-600" :
                      "bg-neutral-100 text-neutral-500"
                    }`}>
                      {order.status}
                    </span>
                  </Link>
                ))}
              </div>
            ) : (
              <div className="text-center py-8">
                <Package size={28} className="text-neutral-300 mx-auto mb-3" />
                <p className="text-sm text-neutral-500">You haven't made any purchases yet.</p>
                <Link href="/shop" className="mt-3 inline-block text-xs text-navy-700 font-medium hover:underline">
                  Start Shopping →
                </Link>
              </div>
            )}
          </div>

          {/* My Journals - only show if subscribed */}
          {isJournalSubscriber && (
            <div className="bg-white rounded-2xl border border-neutral-200 p-6">
              <div className="flex items-center justify-between mb-5">
                <h2 className="font-semibold text-navy-800">My Journals</h2>
                <Link href="/journal/new" className="flex items-center gap-1.5 text-xs font-medium text-navy-700 hover:text-navy-900">
                  <PenLine size={13} /> Write New
                </Link>
              </div>
              {user.journals.length > 0 ? (
                <div className="space-y-3">
                  {user.journals.map((j) => (
                    <div key={j.id} className="flex items-center justify-between p-3 rounded-xl hover:bg-neutral-50 transition-colors">
                      <div className="flex-1 min-w-0 mr-4">
                        <div className="text-sm font-medium text-neutral-800 truncate">{j.title}</div>
                        <div className="text-xs text-neutral-400 mt-0.5">
                          {new Date(j.createdAt).toLocaleDateString("en-MY", { day: "numeric", month: "short", year: "numeric" })}
                        </div>
                      </div>
                      <span className={`text-xs font-medium px-2.5 py-1 rounded-full shrink-0 ${j.status === "published" ? "bg-emerald-50 text-emerald-700" : "bg-neutral-100 text-neutral-500"}`}>
                        {j.status}
                      </span>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8">
                  <BookOpen size={28} className="text-neutral-300 mx-auto mb-3" />
                  <p className="text-sm text-neutral-500">You haven't written any journals yet.</p>
                  <Link href="/journal/new" className="mt-3 inline-block text-xs text-navy-700 font-medium hover:underline">
                    Write Your First Journal →
                  </Link>
                </div>
              )}
            </div>
          )}

          {/* My Applications - only show if subscribed */}
          {isJobSeeker && (
            <div className="bg-white rounded-2xl border border-neutral-200 p-6">
              <div className="flex items-center justify-between mb-5">
                <h2 className="font-semibold text-navy-800">My Applications</h2>
                <Link href="/jobs" className="flex items-center gap-1 text-xs font-medium text-navy-700 hover:text-navy-900">
                  Browse Jobs <ArrowRight size={12} />
                </Link>
              </div>
              {user.jobApplications.length > 0 ? (
                <div className="space-y-3">
                  {user.jobApplications.map((app) => (
                    <div key={app.id} className="flex items-center justify-between p-3 rounded-xl hover:bg-neutral-50 transition-colors">
                      <div className="flex-1 min-w-0 mr-4">
                        <div className="text-sm font-medium text-neutral-800 truncate">{app.job.title}</div>
                        <div className="text-xs text-neutral-400 mt-0.5">{app.job.company}</div>
                      </div>
                      <span className={`text-xs font-medium px-2.5 py-1 rounded-full shrink-0 ${
                        app.status === "shortlisted" ? "bg-emerald-50 text-emerald-700" :
                        app.status === "rejected" ? "bg-red-50 text-red-600" :
                        app.status === "viewed" ? "bg-blue-50 text-blue-700" :
                        "bg-neutral-100 text-neutral-500"
                      }`}>
                        {app.status}
                      </span>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8">
                  <Briefcase size={28} className="text-neutral-300 mx-auto mb-3" />
                  <p className="text-sm text-neutral-500">You haven't applied for any jobs yet.</p>
                  <Link href="/jobs" className="mt-3 inline-block text-xs text-navy-700 font-medium hover:underline">
                    Browse Jobs →
                  </Link>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
