"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { apiFetch } from "@/lib/apiClient";
import { formatNaira, getProgressPercent } from "@/lib/utils";
import { PWAInstallButton } from "@/components/shared/PWAInstallButton";
import type { Booking, Notification } from "@/types";

export default function DashboardPage() {
  const router = useRouter();
  const { user, isLoading, isAuthenticated } = useAuth();
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [dataLoading, setDataLoading] = useState(true);

  useEffect(() => {
    if (!isLoading && !isAuthenticated) router.replace("/login");
  }, [isLoading, isAuthenticated, router]);

  useEffect(() => {
    if (!isAuthenticated) return;
    Promise.all([
      apiFetch<Booking[]>("/bookings")
        .then((d) => setBookings(Array.isArray(d) ? d : []))
        .catch(() => setBookings([])),
      apiFetch<{ notifications: Notification[]; unreadCount: number }>("/notifications/me?unread=false")
        .then((d) => { setNotifications(d.notifications.slice(0, 3)); setUnreadCount(d.unreadCount); })
        .catch(() => {}),
    ]).finally(() => setDataLoading(false));
  }, [isAuthenticated]);

  if (isLoading || !user) {
    return (
      <div className="min-h-screen mesh-bg flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#FED665] border-t-transparent animate-spin" />
      </div>
    );
  }

  const primaryBooking = bookings[0];
  const progressPct = primaryBooking
    ? getProgressPercent(Number(primaryBooking.totalPaid), Number((primaryBooking as any).package?.totalCost ?? 1))
    : 68;
  const circumference = 2 * Math.PI * 42;
  const dashOffset = circumference * (1 - progressPct / 100);

  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return "Good Morning";
    if (h < 17) return "Good Afternoon";
    return "Assalamu Alaikum";
  })();

  const initials = user.fullName.split(" ").map((n) => n[0]).join("").slice(0, 2).toUpperCase();
  const firstName = user.fullName.split(" ")[0];

  return (
    <div className="mesh-bg min-h-screen text-white overflow-x-hidden">
      <div className="spiritual-dust" />

      {/* Top App Bar */}
      <nav className="fixed top-0 w-full z-50 bg-black/10 backdrop-blur-xl border-b border-white/5">
        <div className="flex justify-between items-center px-5 h-20 w-full max-w-[1200px] mx-auto">
          <div className="flex items-center gap-4">
            <div className="w-11 h-11 rounded-full border border-[#FED665]/40 flex items-center justify-center bg-[#FED665]/10">
              <span className="text-[#FED665] font-bold text-sm">{initials}</span>
            </div>
            <span className="font-display-lg text-2xl tracking-tighter text-white luminous-text">Al-Bakkah</span>
          </div>
          <div className="flex items-center gap-1">
            <PWAInstallButton variant="pill-sm" />
            <Link href="/notifications" className="relative">
              <button className="material-symbols-outlined text-[#FED665] p-2 rounded-full hover:bg-white/10 transition-colors">
                notifications
              </button>
              {unreadCount > 0 && (
                <span className="absolute top-1 right-1 w-4 h-4 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center">
                  {unreadCount > 9 ? "9+" : unreadCount}
                </span>
              )}
            </Link>
          </div>
        </div>
      </nav>

      <main className="relative z-10 pt-28 pb-36 px-5 max-w-[1200px] mx-auto">
        {/* Welcome Section */}
        <section className="mb-8">
          <h1 className="font-display-lg text-4xl text-white mb-2 tracking-tight">
            {greeting},{" "}
            <span className="font-extrabold text-[#FED665]">{firstName}</span>
          </h1>
          <p className="text-white/50 tracking-wide">
            Your journey to Mecca is{" "}
            <span className="text-white">{progressPct}% funded</span>.
          </p>
        </section>

        {/* App install nudge — visible right after login, hides once installed */}
        <div className="mb-10">
          <PWAInstallButton variant="card" />
        </div>

        {/* Main Savings Card */}
        <section className="mb-12">
          <div className="dark-glass rounded-[40px] p-8 md:p-10 flex flex-col md:flex-row items-center gap-10 relative overflow-hidden">
            <div className="absolute -top-24 -right-24 w-64 h-64 bg-[#FED665]/10 rounded-full blur-[80px]" />

            {/* Progress Ring */}
            <div className="relative w-48 h-48 flex-shrink-0">
              <svg className="w-full h-full" viewBox="0 0 100 100">
                <circle className="text-white/5" cx="50" cy="50" fill="transparent" r="42" stroke="currentColor" strokeWidth="6" />
                <circle
                  className="holographic-ring progress-ring__circle"
                  cx="50" cy="50" fill="transparent" r="42"
                  stroke="#FED665"
                  strokeDasharray={circumference}
                  strokeDashoffset={dashOffset}
                  strokeLinecap="round"
                  strokeWidth="6"
                />
              </svg>
              <div className="absolute inset-0 flex flex-col items-center justify-center">
                <span className="font-display-lg text-4xl text-white luminous-text">{progressPct}%</span>
                <span className="text-[#FED665]/80 text-[10px] font-semibold uppercase tracking-[0.2em] mt-1">Status</span>
              </div>
            </div>

            {/* Details */}
            <div className="flex-grow text-center md:text-left">
              <div className="mb-6">
                <h2 className="font-display-lg text-5xl text-white mb-2 tracking-tighter luminous-text">
                  {formatNaira(primaryBooking ? Number(primaryBooking.totalPaid) : 1768000)}
                </h2>
                <p className="text-white/40 text-[18px]">
                  Target Amount:{" "}
                  <span className="text-[#FED665]/80 font-bold">
                    {formatNaira(primaryBooking ? Number((primaryBooking as any).package?.totalCost ?? 2600000) : 2600000)}
                  </span>
                </p>
              </div>

              <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 pt-8 border-t border-white/5 w-full">
                <div className="flex items-center gap-3 text-white/60">
                  <span className="material-symbols-outlined text-[#FED665]">event_repeat</span>
                  <span className="text-[14px] font-semibold">
                    Auto-save: <span className="text-white">
                      {primaryBooking ? (primaryBooking as any).package?.name?.split(" ")[0] ?? "Active" : "Set up now"}
                    </span>
                  </span>
                </div>
                <Link
                  href="/deposit"
                  className="px-8 py-4 rounded-full bg-[#FED665] text-[#040b61] font-bold tracking-tight hover:scale-105 active:scale-95 transition-all shadow-[0_10px_30px_rgba(254,214,101,0.2)] inline-block text-center"
                >
                  Deposit Now
                </Link>
              </div>
            </div>
          </div>
        </section>

        {/* Quick Actions Grid */}
        <section className="mb-16">
          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            {[
              {
                icon: "mosque",
                label: "My Package",
                value: primaryBooking ? (primaryBooking as any).package?.name?.split(" ")[0] ?? "Premium" : "Browse",
                href: primaryBooking ? "/transactions" : "/packages",
              },
              {
                icon: "badge",
                iconFilled: true,
                label: "Documents",
                value: "3/4 Ready",
                href: "/profile",
              },
              {
                icon: "receipt_long",
                label: "Payments",
                value: "View History",
                href: "/transactions",
              },
              {
                icon: "support_agent",
                label: "Support",
                value: "Talk to Agent",
                href: "tel:+2348077562271",
              },
              {
                icon: "request_quote",
                label: "Withdrawal",
                value: "Request Funds",
                href: "/withdrawal",
              },
            ].map(({ icon, iconFilled, label, value, href }) => (
              <Link
                key={label}
                href={href}
                className="dark-glass rounded-3xl p-6 hover:-translate-y-2 cursor-pointer group block transition-transform"
              >
                <div className="w-12 h-12 rounded-2xl bg-white/5 flex items-center justify-center mb-5 group-hover:bg-[#FED665]/10 transition-colors">
                  <span
                    className="material-symbols-outlined text-[#FED665]"
                    style={iconFilled ? { fontVariationSettings: "'FILL' 1" } : undefined}
                  >
                    {icon}
                  </span>
                </div>
                <p className="text-[10px] text-white/40 mb-1 uppercase tracking-widest font-semibold">{label}</p>
                <h3 className="font-headline-md text-xl text-white">{value}</h3>
              </Link>
            ))}
          </div>
        </section>

        {/* Pilgrimage Milestones */}
        <section className="mb-10">
          <div className="flex items-end justify-between mb-10">
            <div>
              <h2 className="font-display-lg text-3xl text-white mb-1">Pilgrimage Milestones</h2>
              <p className="text-white/40 text-sm">Tracking your spiritual roadmap</p>
            </div>
            <Link
              href="/transactions"
              className="text-[#FED665] text-[14px] font-semibold hover:text-white transition-colors flex items-center gap-1"
            >
              View Detailed Roadmap
              <span className="material-symbols-outlined text-sm">arrow_forward</span>
            </Link>
          </div>

          <div className="space-y-0 relative pl-4">
            {/* Fiber optic line */}
            <div className="absolute left-[35px] top-6 bottom-6 w-[1px] fiber-optic" />

            {/* Milestone 1 — Active */}
            <div className="flex items-start gap-10 relative pb-16">
              <div className="relative z-10">
                <div className="w-11 h-11 rounded-full bg-black/80 border border-[#FED665] flex items-center justify-center halo-active">
                  <div className="w-2.5 h-2.5 rounded-full bg-[#FED665] shadow-[0_0_15px_#FED665]" />
                </div>
              </div>
              <div className="dark-glass p-6 rounded-2xl flex-grow -mt-2">
                <h4 className="font-headline-md text-white mb-2">Visa Approval</h4>
                <div className="flex items-center gap-3">
                  <span className="px-2.5 py-0.5 rounded-full bg-[#FED665]/10 text-[#FED665] text-[10px] font-bold tracking-[0.2em] uppercase border border-[#FED665]/20">
                    Processing
                  </span>
                  <span className="text-xs text-white/30 italic">Est: July 15</span>
                </div>
              </div>
            </div>

            {/* Milestone 2 — Upcoming */}
            <div className="flex items-start gap-10 relative pb-16 opacity-40">
              <div className="relative z-10">
                <div className="w-11 h-11 rounded-full bg-white/5 border border-white/10 flex items-center justify-center">
                  <div className="w-2 h-2 rounded-full bg-white/20" />
                </div>
              </div>
              <div className="dark-glass p-6 rounded-2xl flex-grow -mt-2">
                <h4 className="font-headline-md text-white/70">Flight Booking</h4>
                <span className="text-xs text-white/30 font-bold tracking-widest uppercase">Upcoming</span>
              </div>
            </div>

            {/* Milestone 3 — Planned */}
            <div className="flex items-start gap-10 relative opacity-20">
              <div className="relative z-10">
                <div className="w-11 h-11 rounded-full bg-white/5 border border-white/10 flex items-center justify-center">
                  <div className="w-2 h-2 rounded-full bg-white/20" />
                </div>
              </div>
              <div className="dark-glass p-6 rounded-2xl flex-grow -mt-2">
                <h4 className="font-headline-md text-white/70">Hotel Confirmation</h4>
                <span className="text-xs text-white/30 font-bold tracking-widest uppercase">Planned</span>
              </div>
            </div>
          </div>
        </section>

      </main>
    </div>
  );
}
