"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  UserRound,
  KeyRound,
  Settings,
  ReceiptText,
  BellRing,
  CircleHelp,
  LogOut,
  ChevronRight,
  Clock3,
  PackageCheck,
  XCircle,
} from "lucide-react";
import { GlassCard } from "@/components/ui/GlassCard";
import { NetworkBadge } from "@/components/NetworkBadge";
import { StatusPill } from "@/components/ui/StatusPill";
import { Skeleton } from "@/components/ui/Skeleton";
import { useAuth } from "@/lib/auth/auth-provider";
import { fetchUserOrders } from "@/lib/data/orders";
import { useSettings } from "@/lib/data/settings-provider";
import { Order } from "@/lib/types";
import { cn } from "@/lib/cn";
import { useTranslation } from "@/lib/i18n/LanguageProvider";
import { formatDate } from "@/lib/i18n/format-date";
import { Language } from "@/lib/i18n/translations";

function initialsFor(name: string | null | undefined, email: string | undefined) {
  if (name?.trim()) {
    return name
      .trim()
      .split(/\s+/)
      .map((p) => p[0])
      .slice(0, 2)
      .join("")
      .toUpperCase();
  }
  return email?.slice(0, 2).toUpperCase() ?? "?";
}

function memberSince(iso: string | undefined, language: Language) {
  if (!iso) return null;
  return formatDate(iso, language, { day: undefined, month: "long", year: "numeric" });
}

export default function ProfilePage() {
  const router = useRouter();
  const { user, profile, signOut } = useAuth();
  const { t, language } = useTranslation();
  const { settings } = useSettings();
  const [loggingOut, setLoggingOut] = useState(false);
  const [orders, setOrders] = useState<Order[]>([]);
  const [loadingOrders, setLoadingOrders] = useState(true);

  const MENU = [
    { href: "/profile/edit", label: t("profile.editProfile"), icon: UserRound },
    { href: "/change-password", label: t("profile.changePassword"), icon: KeyRound },
    { href: "/notifications", label: t("profile.notificationCenter"), icon: BellRing },
    { href: "/settings", label: t("profile.settings"), icon: Settings },
    { href: "/help", label: t("profile.helpSupport"), icon: CircleHelp },
  ];

  // Same three categories as the request, not all four DB statuses —
  // "Approved" still shows in Recent Orders and the full Order History
  // filter, it just isn't one of the headline stat chips here.
  const STAT_CONFIG = {
    pending: { label: t("profile.pending"), icon: Clock3, className: "bg-gold/15 text-gold-dim dark:text-gold-bright" },
    completed: { label: t("profile.completed"), icon: PackageCheck, className: "bg-teal/15 text-teal-dim dark:text-teal" },
    rejected: { label: t("profile.rejected"), icon: XCircle, className: "bg-danger/15 text-danger" },
  } as const;

  const displayName = profile?.full_name || user?.email?.split("@")[0] || t("profile.defaultName");
  const displayPhone = profile?.phone || user?.email || "";

  useEffect(() => {
    if (!user) return;
    let active = true;
    fetchUserOrders()
      .then((result) => active && setOrders(result))
      .finally(() => active && setLoadingOrders(false));
    return () => {
      active = false;
    };
  }, [user]);

  const counts = useMemo(
    () => ({
      pending: orders.filter((o) => o.status === "pending").length,
      completed: orders.filter((o) => o.status === "completed").length,
      rejected: orders.filter((o) => o.status === "rejected").length,
    }),
    [orders]
  );

  // Most recent order still in flight — same definition Home's widget
  // uses, derived here from the same fetch instead of a second query.
  const activeOrder = orders.find((o) => o.status === "pending" || o.status === "approved");
  const recentOrders = orders.slice(0, 3);

  async function handleLogout() {
    setLoggingOut(true);
    await signOut();
    router.push("/welcome");
  }

  return (
    <div className="flex flex-col gap-6 px-4 pt-safe">
      <header className="flex items-center gap-4 pt-2">
        <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-3xl bg-gradient-to-br from-gold-bright to-gold-dim font-display text-xl font-bold text-ink shadow-glow-gold">
          {initialsFor(profile?.full_name, user?.email)}
        </div>
        <div className="min-w-0">
          <h1 className="truncate font-display text-lg font-semibold">{displayName}</h1>
          <p className="truncate text-sm text-muted">{displayPhone}</p>
          {memberSince(profile?.created_at, language) && (
            <p className="mt-0.5 text-xs text-muted/70">{t("profile.memberSince")} {memberSince(profile?.created_at, language)}</p>
          )}
        </div>
      </header>

      <section>
        <p className="mb-3 text-sm font-medium text-muted">{t("profile.ordersAtAGlance")}</p>
        {loadingOrders ? (
          <div className="grid grid-cols-3 gap-3">
            <Skeleton className="h-20 w-full !rounded-3xl" />
            <Skeleton className="h-20 w-full !rounded-3xl" />
            <Skeleton className="h-20 w-full !rounded-3xl" />
          </div>
        ) : (
          <div className="grid grid-cols-3 gap-3">
            {(Object.keys(STAT_CONFIG) as (keyof typeof STAT_CONFIG)[]).map((key) => {
              const { label, icon: Icon, className } = STAT_CONFIG[key];
              return (
                <Link
                  key={key}
                  href={`/orders?status=${key}`}
                  className="flex flex-col items-center gap-1.5 rounded-3xl glass px-2 py-4 text-center active:scale-95 transition-transform"
                >
                  <span className={cn("flex h-9 w-9 items-center justify-center rounded-2xl", className)}>
                    <Icon size={16} strokeWidth={2} />
                  </span>
                  <span className="tnum font-display text-lg font-bold">{counts[key]}</span>
                  <span className="text-[11px] text-muted">{label}</span>
                </Link>
              );
            })}
          </div>
        )}
      </section>

      {activeOrder && (
        <section>
          <p className="mb-3 text-sm font-medium text-muted">{t("profile.currentOrderStatus")}</p>
          <Link href={`/orders/${activeOrder.id}`}>
            <GlassCard strong className="flex items-center justify-between">
              <div className="min-w-0">
                <div className="flex items-center gap-2">
                  <NetworkBadge network={activeOrder.network} size="sm" />
                  <h3 className="truncate font-display text-[15px] font-semibold">
                    {activeOrder.packageName}
                  </h3>
                </div>
                <p className="mt-1.5 text-xs text-muted">{activeOrder.id}</p>
              </div>
              <StatusPill status={activeOrder.status} />
            </GlassCard>
          </Link>
        </section>
      )}

      <section>
        <div className="mb-3 flex items-center justify-between">
          <p className="text-sm font-medium text-muted">{t("profile.recentOrders")}</p>
          <Link href="/orders" className="text-xs font-semibold text-gold-dim dark:text-gold-bright">
            {t("profile.seeAll")}
          </Link>
        </div>
        {loadingOrders ? (
          <div className="flex flex-col gap-3">
            <Skeleton className="h-16 w-full !rounded-4xl" />
            <Skeleton className="h-16 w-full !rounded-4xl" />
          </div>
        ) : recentOrders.length === 0 ? (
          <GlassCard className="flex flex-col items-center gap-1 py-6 text-center">
            <ReceiptText size={20} className="text-muted" />
            <p className="mt-1 text-sm text-muted">{t("profile.noOrdersYet")}</p>
          </GlassCard>
        ) : (
          <div className="flex flex-col gap-3">
            {recentOrders.map((order) => (
              <Link
                key={order.id}
                href={`/orders/${order.id}`}
                className="flex items-center gap-3 rounded-4xl glass px-4 py-3.5 active:scale-[0.985] transition-transform"
              >
                <NetworkBadge network={order.network} size="sm" />
                <div className="min-w-0 flex-1">
                  <h4 className="truncate text-[13px] font-semibold">{order.packageName}</h4>
                  <p className="mt-0.5 text-[11px] text-muted">{formatDate(order.createdAt, language)}</p>
                </div>
                <StatusPill status={order.status} />
              </Link>
            ))}
          </div>
        )}
      </section>

      <GlassCard className="flex flex-col divide-y divide-black/5 !p-2 dark:divide-white/5">
        {MENU.map(({ href, label, icon: Icon }) => (
          <Link
            key={label}
            href={href}
            className="flex items-center gap-3 px-3 py-3.5 first:rounded-t-3xl last:rounded-b-3xl active:bg-black/5 dark:active:bg-white/5"
          >
            <span className="flex h-9 w-9 items-center justify-center rounded-xl bg-black/5 dark:bg-white/5">
              <Icon size={17} strokeWidth={2} className="text-muted" />
            </span>
            <span className="flex-1 text-sm font-medium">{label}</span>
            <ChevronRight size={16} className="text-muted" />
          </Link>
        ))}
      </GlassCard>

      <button
        type="button"
        onClick={handleLogout}
        disabled={loggingOut}
        className="flex items-center justify-center gap-2 rounded-3xl border border-danger/30 bg-danger/10 px-4 py-3.5 text-sm font-semibold text-danger disabled:opacity-50"
      >
        <LogOut size={16} strokeWidth={2.5} />
        {loggingOut ? t("profile.loggingOut") : t("profile.logOut")}
      </button>

      <p className="pb-4 text-center text-xs text-muted">{settings.businessName} &middot; v{settings.appVersion}</p>
    </div>
  );
}
