import type { ReactNode } from 'react';
import { BadgeCheck, type LucideIcon } from 'lucide-react';
import Link from '@rutatiina/ui/components/common/link';
import {
  Avatar,
  AvatarFallback,
  AvatarImage,
} from '@rutatiina/ui/components/ui/avatar';
import { Icon } from '@rutatiina/ui/lib/icons';
import { toAbsoluteUrl } from '@rutatiina/ui/lib/helpers';
import { usePathname } from '@rutatiina/ui/lib/navigation';
import { cn } from '@rutatiina/ui/lib/utils';
import { useTheme } from '@rutatiina/ui/providers/theme-provider';
import type { MenuConfig } from '@rutatiina/ui/types/navigation';
import { Container } from '@rutatiina/themes/components/container';
import { useAppMenu } from '@rutatiina/themes/hooks/use-app-menu';

export type ProfileHeroMeta = {
  icon?: LucideIcon;
  label: string;
};

export type ProfileHeroUser = {
  name: string;
  avatar_url: string | null;
  initials: string;
  verified?: boolean;
};

/** The tab whose path is the longest prefix of the current pathname. */
function activeTabPath(tabs: MenuConfig, pathname: string): string | undefined {
  return tabs
    .map((tab) => tab.path)
    .filter(
      (path): path is string =>
        !!path && (pathname === path || pathname.startsWith(`${path}/`)),
    )
    .sort((a, b) => b.length - a.length)[0];
}

/**
 * The header shared by the account pages: cover image, ringed avatar, name,
 * a meta row and the tab bar (the server-built "account.tabs" menu), followed
 * by the page content.
 */
export function ProfileHero({
  user,
  meta = [],
  children,
}: {
  user: ProfileHeroUser;
  meta?: ProfileHeroMeta[];
  children: ReactNode;
}) {
  const { theme } = useTheme();
  const { accountTabs } = useAppMenu();
  const pathname = usePathname();
  const active = activeTabPath(accountTabs, pathname);

  return (
    <>
      <div
        className="bg-cover bg-center bg-no-repeat"
        style={{
          backgroundImage: `url('${toAbsoluteUrl(
            theme === 'dark'
              ? '/media/images/2600x1200/bg-1-dark.png'
              : '/media/images/2600x1200/bg-1.png',
          )}')`,
        }}
      >
        <Container>
          <div className="flex flex-col items-center gap-2 py-4 lg:gap-3.5 lg:pt-[var(--app-space-5,1.25rem)] lg:pb-6">
            <Avatar
              key={user.avatar_url}
              className="size-[100px] rounded-full border-3 border-green-500"
            >
              {user.avatar_url && (
                <AvatarImage src={user.avatar_url} alt={user.name} />
              )}
              <AvatarFallback className="text-2xl">
                {user.initials}
              </AvatarFallback>
            </Avatar>
            <div className="flex items-center gap-1.5">
              <div className="text-mono text-lg leading-5 font-semibold">
                {user.name}
              </div>
              {user.verified && (
                <BadgeCheck
                  className="text-primary size-4"
                  aria-label="Verified"
                />
              )}
            </div>
            <div className="flex flex-wrap justify-center gap-1 text-sm lg:gap-4.5">
              {meta.map(({ icon: MetaIcon, label }) => (
                <div className="flex items-center gap-1.25" key={label}>
                  {MetaIcon && (
                    <MetaIcon size={16} className="text-muted-foreground" />
                  )}
                  <span className="text-secondary-foreground font-medium">
                    {label}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </Container>
      </div>
      <Container>
        {accountTabs.length > 0 && (
          <div className="border-border mb-[var(--app-space-5,1.25rem)] border-b lg:mb-6">
            <nav className="kt-scrollable-x-auto flex items-stretch gap-3">
              {accountTabs.map((tab) => (
                <Link
                  key={tab.path}
                  href={tab.path ?? ''}
                  data-active={tab.path === active || undefined}
                  className={cn(
                    'text-secondary-foreground flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2.5 text-sm whitespace-nowrap',
                    'hover:text-primary',
                    'data-[active=true]:text-primary data-[active=true]:border-primary',
                  )}
                >
                  {tab.icon && <Icon name={tab.icon} className="size-4" />}
                  {tab.title}
                </Link>
              ))}
            </nav>
          </div>
        )}
        {children}
      </Container>
    </>
  );
}
