"use client";

import * as React from "react";
import { Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  User,
  Shield,
  ShieldCheck,
  ShieldAlert,
  KeyRound,
  Settings,
} from "lucide-react";
import { ProfilePanel } from "@/components/admin/panels/profile-panel";
import { SecurityPanel } from "@/components/admin/panels/security-panel";
import { MyRolePanel } from "@/components/admin/panels/my-role-panel";
import { RolesPanel } from "@/components/admin/panels/roles-panel";
import { ResetRequestsPanel } from "@/components/admin/panels/reset-requests-panel";
import { SecurityAuditPanel } from "@/components/admin/panels/security-audit-panel";
import { SystemSecurityPanel } from "@/components/admin/panels/system-security-panel";
import { useAdminAuth } from "@/components/admin/admin-auth-provider";

interface Me {
  level: "MAIN_ADMIN" | "SUB_ADMIN";
  permissions: string[];
}

interface TabDef {
  key: string;
  label: string;
  icon: React.ComponentType<{ className?: string }>;
  show: (m: Me) => boolean;
  render: () => React.ReactNode;
}

// Tab VISIBILITY is permission-aware here, but it is ONLY UX — every panel's data
// comes from an API that independently enforces the same authorization
// server-side (a sub-admin who forces ?tab=audit still gets 403 from the API).
const TABS: TabDef[] = [
  { key: "profile", label: "Profile", icon: User, show: () => true, render: () => <ProfilePanel /> },
  { key: "security", label: "Security", icon: Shield, show: () => true, render: () => <SecurityPanel /> },
  {
    key: "my-role",
    label: "My Role",
    icon: ShieldCheck,
    show: (m) => m.level !== "MAIN_ADMIN",
    render: () => <MyRolePanel />,
  },
  {
    key: "roles",
    label: "Roles & Permissions",
    icon: Shield,
    show: (m) => m.level === "MAIN_ADMIN" || m.permissions.includes("roles.manage"),
    render: () => <RolesPanel />,
  },
  {
    key: "reset",
    label: "Reset Requests",
    icon: KeyRound,
    show: (m) => m.level === "MAIN_ADMIN" || m.permissions.includes("security.manage_reset_requests"),
    render: () => <ResetRequestsPanel />,
  },
  {
    key: "audit",
    label: "Security Audit",
    icon: ShieldAlert,
    show: (m) => m.level === "MAIN_ADMIN" || m.permissions.includes("security.view_audit"),
    render: () => <SecurityAuditPanel />,
  },
  {
    key: "system",
    label: "System Security",
    icon: Settings,
    show: (m) => m.level === "MAIN_ADMIN" || m.permissions.includes("security.manage_settings"),
    render: () => <SystemSecurityPanel />,
  },
];

function AccountCenter() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { user, permissions, isAuthenticated, isLoading } = useAdminAuth();

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

  const me = React.useMemo<Me | null>(() => {
    if (!user) return null;
    return {
      level: user.level,
      permissions: permissions || [],
    };
  }, [user, permissions]);

  const visibleTabs = React.useMemo(() => (me ? TABS.filter((t) => t.show(me)) : []), [me]);

  const requested = searchParams.get("tab") || "profile";
  const activeKey = visibleTabs.some((t) => t.key === requested)
    ? requested
    : visibleTabs[0]?.key || "profile";
  const activeTab = visibleTabs.find((t) => t.key === activeKey);

  const selectTab = (key: string) => {
    const params = new URLSearchParams(Array.from(searchParams.entries()));
    params.set("tab", key);
    router.replace(`/admin/profile?${params.toString()}`, { scroll: false });
  };


  if (isLoading) {
    return <div className="py-12 text-center text-xs text-neutral-400">Loading profile…</div>;
  }
  if (!me) {
    return (
      <div className="rounded-xl border border-neutral-200 bg-neutral-50 p-4 text-xs text-neutral-600 dark:border-neutral-800 dark:bg-neutral-900 dark:text-neutral-400">
        Session expired. Redirecting to login...
      </div>
    );
  }

  return (
    <div className="max-w-5xl">
      <div className="mb-6">
        <h1 className="text-xl font-bold tracking-tight text-neutral-900 dark:text-white">My Profile</h1>
        <p className="mt-0.5 text-xs text-neutral-500">
          Your account, author profile, security and access — all in one place.
        </p>
      </div>

      {/* Tabs — horizontally scrollable on mobile */}
      <div
        role="tablist"
        aria-label="Account center sections"
        className="mb-6 flex gap-1 overflow-x-auto border-b border-neutral-200 pb-px dark:border-neutral-800"
      >
        {visibleTabs.map((t) => {
          const Icon = t.icon;
          const isActive = t.key === activeKey;
          return (
            <button
              key={t.key}
              role="tab"
              type="button"
              aria-selected={isActive}
              onClick={() => selectTab(t.key)}
              className={`inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap border-b-2 px-3.5 py-2.5 text-xs font-semibold transition-colors ${
                isActive
                  ? "border-neutral-900 text-neutral-900 dark:border-white dark:text-white"
                  : "border-transparent text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
              }`}
            >
              <Icon className="h-3.5 w-3.5" />
              {t.label}
            </button>
          );
        })}
      </div>

      <div role="tabpanel">{activeTab?.render()}</div>
    </div>
  );
}

export default function AdminAccountCenterPage() {
  return (
    <Suspense fallback={<div className="py-12 text-center text-xs text-neutral-400">Loading…</div>}>
      <AccountCenter />
    </Suspense>
  );
}
