"use client";

import Link from "next/link";
import { useAuth } from "@/hooks/useAuth";
import { useHeaderSession } from "@/hooks/useHeaderSession";
import { useTenantHost } from "@/hooks/useTenantHost";
import { useTheme } from "@/hooks/useTheme";
import { Button, Container } from "@/components/ui";

export function SiteHeader() {
  const { theme } = useTheme();
  const host = useTenantHost();
  const { login, loading, user } = useAuth();
  const { isSsoAuth, isLoggedIn } = useHeaderSession();
  const isPlatformAdmin =
    user?.roles?.includes("platform_admin") || user?.roles?.includes("tenant_admin");

  const brandName = host.isTenantHost
    ? theme?.site_name ?? "Workspace"
    : theme?.site_name ?? "Torbatyar";
  const brandSub = host.isTenantHost ? "workspace روی تربت‌یار" : "پلتفرم SaaS چندسرویسی";

  return (
    <header className="sticky top-0 z-50 border-b border-gray-100/80 bg-white/80 backdrop-blur-md">
      <Container className="flex h-16 items-center justify-between gap-4">
        <Link href="/" className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary text-lg font-bold text-white shadow-md">
            {brandName.charAt(0)}
          </div>
          <div className="hidden sm:block">
            <p className="text-base font-bold text-secondary">{brandName}</p>
            <p className="text-xs text-gray-500">{brandSub}</p>
          </div>
        </Link>

        <nav className="flex flex-wrap items-center justify-end gap-2">
          {isLoggedIn ? (
            <>
              {!host.isTenantHost && isSsoAuth && isPlatformAdmin && (
                <Link href="/admin">
                  <Button variant="primary" size="sm">
                    پنل ادمین
                  </Button>
                </Link>
              )}
              {isSsoAuth && (
                <Link href="/dashboard">
                  <Button variant="outline" size="sm">
                    داشبورد
                  </Button>
                </Link>
              )}
              {isSsoAuth && (
                <Link
                  href={
                    isPlatformAdmin && !host.isTenantHost
                      ? "/admin/settings"
                      : "/dashboard/settings"
                  }
                >
                  <Button variant="ghost" size="sm">
                    حساب کاربری
                  </Button>
                </Link>
              )}
            </>
          ) : (
            <Button
              variant="primary"
              size="sm"
              onClick={() => login()}
              loading={loading}
              loadingText="..."
            >
              ورود
            </Button>
          )}
        </nav>
      </Container>
    </header>
  );
}
