"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Bell } from "lucide-react";
import { ThemeToggle } from "@/components/ui/ThemeToggle";
import { NetworkBadge } from "@/components/NetworkBadge";
import { PackageCard } from "@/components/PackageCard";
import { StatusPill } from "@/components/ui/StatusPill";
import { GlassCard } from "@/components/ui/GlassCard";
import { Skeleton } from "@/components/ui/Skeleton";
import { NETWORKS } from "@/lib/mock-data";
import { fetchActivePackages } from "@/lib/data/packages";
import { fetchActiveOrder } from "@/lib/data/orders";
import { fetchUnreadNotificationCount, NOTIFICATION_POLL_MS } from "@/lib/data/notifications";
import { useAuth } from "@/lib/auth/auth-provider";
import { useTranslation } from "@/lib/i18n/LanguageProvider";
import { Package, Order } from "@/lib/types";

export default function HomePage() {
  const { user, profile } = useAuth();
  const { t } = useTranslation();
  const displayName = profile?.full_name || user?.email?.split("@")[0] || "there";
  const [featured, setFeatured] = useState<Package[]>([]);
  const [activeOrder, setActiveOrder] = useState<Order | null>(null);
  const [loadingPackages, setLoadingPackages] = useState(true);
  const [unreadNotifications, setUnreadNotifications] = useState(0);

  useEffect(() => {
    let active = true;

    fetchActivePackages()
      .then((result) => active && setFeatured(result.slice(0, 3)))
      .finally(() => active && setLoadingPackages(false));

    if (user) {
      fetchActiveOrder().then((result) => active && setActiveOrder(result));
    }

    return () => {
      active = false;
    };
  }, [user]);

  useEffect(() => {
    if (!user) return;
    const refreshUnread = () => fetchUnreadNotificationCount().then(setUnreadNotifications);

    refreshUnread();
    // Polling, not a WebSocket/Realtime subscription — see
    // NOTIFICATION_POLL_MS's own comment in lib/data/notifications.ts.
    // Also refresh on window focus, so switching back to this tab
    // updates the badge immediately rather than waiting for the next
    // tick.
    const interval = setInterval(refreshUnread, NOTIFICATION_POLL_MS);
    window.addEventListener("focus", refreshUnread);
    return () => {
      clearInterval(interval);
      window.removeEventListener("focus", refreshUnread);
    };
  }, [user]);

  return (
    <div className="flex flex-col gap-6 px-4 pt-safe">
      <header className="flex items-center justify-between pt-2">
        <div>
          <p className="text-sm text-muted">{t("home.greeting")}</p>
          <h1 className="font-display text-xl font-semibold tracking-tight">
            {displayName}
          </h1>
        </div>
        <div className="flex items-center gap-2">
          <Link
            href="/notifications"
            aria-label="Notifications"
            className="relative flex h-10 w-10 items-center justify-center rounded-full glass"
          >
            <Bell size={18} strokeWidth={2} />
            {unreadNotifications > 0 && (
              <span className="absolute right-2 top-2 h-2 w-2 rounded-full bg-danger" />
            )}
          </Link>
          <ThemeToggle />
        </div>
      </header>

      <section>
        <p className="mb-3 text-sm font-medium text-muted">{t("home.chooseNetwork")}</p>
        <div className="grid grid-cols-3 gap-3">
          {NETWORKS.map((n) => (
            <Link
              key={n.id}
              href={`/packages?network=${n.id}`}
              className="flex flex-col items-center gap-2 rounded-4xl glass px-3 py-4 active:scale-95 transition-transform"
            >
              <NetworkBadge network={n.id} size="md" />
              <span className="text-xs font-semibold">{n.label}</span>
            </Link>
          ))}
        </div>
      </section>

      {activeOrder && (
        <section>
          <Link href={`/orders/${activeOrder.id}`}>
            <GlassCard strong className="flex items-center justify-between">
              <div className="min-w-0">
                <p className="text-[11px] font-medium uppercase tracking-wide text-muted">
                  {t("home.trackOrder")}
                </p>
                <h3 className="truncate font-display text-[15px] font-semibold">
                  {activeOrder.packageName}
                </h3>
                <p className="mt-1 text-xs text-muted">{activeOrder.id}</p>
              </div>
              <StatusPill status={activeOrder.status} />
            </GlassCard>
          </Link>
        </section>
      )}

      <section className="flex flex-col gap-3">
        <div className="flex items-center justify-between">
          <p className="text-sm font-medium text-muted">{t("home.popularPackages")}</p>
          <Link href="/packages" className="text-xs font-semibold text-gold-dim dark:text-gold-bright">
            {t("common.seeAll")}
          </Link>
        </div>
        <div className="flex flex-col gap-4">
          {loadingPackages ? (
            <>
              <Skeleton className="h-48 w-full !rounded-4xl" />
              <Skeleton className="h-48 w-full !rounded-4xl" />
              <Skeleton className="h-48 w-full !rounded-4xl" />
            </>
          ) : (
            featured.map((pkg, i) => <PackageCard key={pkg.id} pkg={pkg} index={i} />)
          )}
        </div>
      </section>
    </div>
  );
}
