"use client";

import Link from "next/link";
import { useState } from "react";
import { ROUTES } from "@/config/routes.config";
import type {
  NavbarSubscription,
  NavbarUser,
} from "@/components/layout/NavbarInteractive";

const STATUS_LABELS: Record<string, string> = {
  trial: "Trial",
  active: "Active",
  cancelled: "Cancelled",
  expired: "Expired",
};

const PLAN_PALETTE: Record<string, string> = {
  free: "bg-slate-100 text-slate-700",
  starter: "bg-rose-100 text-rose-700",
  pro: "bg-fuchsia-100 text-fuchsia-700",
  premium: "bg-amber-100 text-amber-700",
  enterprise: "bg-indigo-100 text-indigo-700",
};

export function ProfilePanel({
  user,
  subscription,
  onClose,
}: {
  user: NavbarUser;
  subscription: NavbarSubscription | null;
  onClose: () => void;
}) {
  const [signingOut, setSigningOut] = useState(false);

  const initials = user.name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]?.toUpperCase() ?? "")
    .join("");

  const planKey = subscription?.planSlug?.toLowerCase() ?? "free";
  const planClass = PLAN_PALETTE[planKey] ?? "bg-rose-100 text-rose-700";
  const statusKey = subscription?.status?.toLowerCase() ?? "";
  const statusLabel = STATUS_LABELS[statusKey] ?? (subscription ? subscription.status : "No plan");

  const expires = subscription?.endDate ?? subscription?.trialEndsAt ?? null;
  const expiresLabel = expires
    ? new Date(expires).toLocaleDateString("en-US", {
        month: "short",
        day: "numeric",
        year: "numeric",
      })
    : null;

  const logout = async () => {
    setSigningOut(true);
    try {
      await fetch("/api/auth/logout", { method: "POST" });
    } catch {
      // ignore
    }
    window.location.href = ROUTES.login;
  };

  return (
    <div className="max-h-[80vh] overflow-hidden overflow-y-auto rounded-2xl border border-rose-100 bg-white shadow-2xl shadow-rose-500/15">
      <div className="relative bg-gradient-to-br from-rose-500 via-pink-600 to-fuchsia-600 px-4 py-4 text-white">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-3">
            {user.avatar ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={user.avatar}
                alt={user.name}
                className="h-12 w-12 rounded-full object-cover ring-2 ring-white/40"
              />
            ) : (
              <span className="grid h-12 w-12 place-items-center rounded-full bg-white/15 text-base font-semibold ring-2 ring-white/30">
                {initials || "??"}
              </span>
            )}
            <div>
              <p className="text-sm font-semibold leading-tight">{user.name}</p>
              <p className="text-[11px] text-white/80">{user.email}</p>
            </div>
          </div>
          <button
            type="button"
            onClick={onClose}
            aria-label="Close profile"
            className="rounded p-1 text-white/80 hover:bg-white/10 hover:text-white"
          >
            ✕
          </button>
        </div>

        <div className="mt-3 flex items-center gap-2">
          <span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${planClass}`}>
            {subscription?.planName ?? "Free"} plan
          </span>
          <span className="rounded-full bg-white/20 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-white">
            {statusLabel}
          </span>
        </div>
        {expiresLabel ? (
          <p className="mt-2 text-[11px] text-white/85">
            {statusKey === "trial" ? "Trial ends" : "Renews"} on {expiresLabel}
          </p>
        ) : (
          <p className="mt-2 text-[11px] text-white/85">No active subscription</p>
        )}
      </div>

      <div className="p-3">
        <ul className="space-y-1 text-sm">
          <li>
            <Link
              href="/dashboard"
              className="flex items-center gap-2 rounded-lg px-3 py-2 text-foreground hover:bg-rose-50"
            >
              <DashboardIcon className="h-4 w-4 text-rose-500" />
              Dashboard
            </Link>
          </li>
          <li>
            <Link
              href="/events"
              className="flex items-center gap-2 rounded-lg px-3 py-2 text-foreground hover:bg-rose-50"
            >
              <EventsIcon className="h-4 w-4 text-rose-500" />
              My events
            </Link>
          </li>
          <li>
            <Link
              href="/templates"
              className="flex items-center gap-2 rounded-lg px-3 py-2 text-foreground hover:bg-rose-50"
            >
              <TemplatesIcon className="h-4 w-4 text-rose-500" />
              Browse templates
            </Link>
          </li>
          <li>
            <Link
              href="/pricing"
              className="flex items-center gap-2 rounded-lg px-3 py-2 text-foreground hover:bg-rose-50"
            >
              <PlanIcon className="h-4 w-4 text-rose-500" />
              Subscription &amp; billing
            </Link>
          </li>
        </ul>

        <button
          type="button"
          onClick={logout}
          disabled={signingOut}
          className="mt-2 flex w-full items-center justify-center gap-2 rounded-lg border border-rose-200 bg-white px-3 py-2 text-sm font-medium text-rose-600 hover:bg-rose-50 disabled:opacity-60"
        >
          <LogoutIcon className="h-4 w-4" />
          {signingOut ? "Signing out…" : "Sign out"}
        </button>
      </div>
    </div>
  );
}

function DashboardIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <rect x="3" y="3" width="7" height="9" rx="1" />
      <rect x="14" y="3" width="7" height="5" rx="1" />
      <rect x="14" y="12" width="7" height="9" rx="1" />
      <rect x="3" y="16" width="7" height="5" rx="1" />
    </svg>
  );
}
function EventsIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <rect x="3" y="5" width="18" height="16" rx="2" />
      <path d="M16 3v4M8 3v4M3 11h18" />
    </svg>
  );
}
function TemplatesIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <rect x="3" y="3" width="7" height="7" rx="1" />
      <rect x="14" y="3" width="7" height="7" rx="1" />
      <rect x="3" y="14" width="7" height="7" rx="1" />
      <rect x="14" y="14" width="7" height="7" rx="1" />
    </svg>
  );
}
function PlanIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M12 2 4 6v6c0 5 3.5 9 8 10 4.5-1 8-5 8-10V6Z" />
      <path d="m9 12 2 2 4-4" />
    </svg>
  );
}
function LogoutIcon(props: React.SVGProps<SVGSVGElement>) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...props}>
      <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
      <path d="m16 17 5-5-5-5" />
      <path d="M21 12H9" />
    </svg>
  );
}
