import { Link } from 'react-router'
import type { AppBskyActorDefs } from '@atproto/api'
import humanFormat from 'human-format'
import Avatar from './Avatar'
import BioText from './BioText'

interface ProfileHeaderProps {
  profile: AppBskyActorDefs.ProfileViewDetailed
  linkTo?: string
}

export default function ProfileHeader({ profile, linkTo }: ProfileHeaderProps) {
  return (
    <>
      {profile.banner && (
        <div className="h-24 rounded-xl overflow-hidden">
          <img src={profile.banner} alt="" className="w-full h-full object-cover" />
        </div>
      )}

      <div className="flex items-center gap-4">
        <Avatar src={profile.avatar} alt={profile.displayName ?? profile.handle} size="md" />
        <div className="min-w-0">
          {profile.displayName && (
            <p className="font-display font-semibold text-stone-900 dark:text-white truncate">
              {profile.displayName}
            </p>
          )}
          {linkTo ? (
            <Link to={linkTo} className="text-sm text-stone-500 dark:text-stone-400 truncate hover:text-stone-700 dark:hover:text-stone-200 transition-colors">@{profile.handle}</Link>
          ) : (
            <p className="text-sm text-stone-500 dark:text-stone-400 truncate">@{profile.handle}</p>
          )}
        </div>
      </div>

      {profile.description && (
        <BioText
          text={profile.description}
          className="text-sm text-stone-700 dark:text-stone-300 leading-relaxed whitespace-pre-wrap"
        />
      )}

      <a
        href={`https://bsky.app/profile/${profile.handle}`}
        target="_blank"
        rel="noopener noreferrer"
        className="inline-flex"
        aria-label={`@${profile.handle} on Bluesky`}
      >
        <img src="/Bluesky_Logo.svg" alt="Bluesky" className="h-5 w-auto" />
      </a>

      <div className="flex gap-6 text-sm">
        {/* <Stat label="Posts" value={profile.postsCount ?? 0} /> */}
        <Stat label="Followers" value={profile.followersCount ?? 0} />
        <Stat label="Following" value={profile.followsCount ?? 0} />
      </div>
    </>
  )
}

function Stat({ label, value }: { label: string; value: number }) {
  return (
    <div>
      <span className="font-semibold text-stone-900 dark:text-white" title={value.toLocaleString()}>
        {humanFormat(value, { maxDecimals: 1, separator: '' })}
      </span>{' '}
      <span className="text-stone-500 dark:text-stone-400">{label}</span>
    </div>
  )
}
