'use client';

import {useState} from 'react';
import Image from 'next/image';
import {UserProfile} from '@/lib/atproto';
import {ChevronDownIcon, ChevronUpIcon} from '@heroicons/react/24/solid';

interface UserListProps {
  users: UserProfile[];
}

export function UserList({users}: UserListProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const INITIAL_COUNT = 8;
  const displayedUsers = isExpanded ? users : users.slice(0, INITIAL_COUNT);
  const hasMore = users.length > INITIAL_COUNT;

  const colors = [
    'bg-red-400',
    'bg-blue-400',
    'bg-yellow-400',
    'bg-green-400',
    'bg-purple-400',
    'bg-pink-400',
    'bg-orange-400',
    'bg-cyan-400',
  ];

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {displayedUsers.map((user, index) => {
          const isInvalidHandle = user.handle.endsWith('.invalid') || user.handle === user.did;
          const bskyAppUrlRaw = process.env.NEXT_PUBLIC_BSKY_APP_URL || 'https://bsky.app';
          const bskyAppUrl = bskyAppUrlRaw.startsWith('http')
            ? bskyAppUrlRaw
            : `https://${bskyAppUrlRaw}`;
          const profileUrl = isInvalidHandle
            ? `${bskyAppUrl}/profile/${user.did}`
            : `${bskyAppUrl}/profile/${user.handle}`;
          const avatarInitial = isInvalidHandle ? '⚠️' : user.handle[0]?.toUpperCase() || '?';

          return (
            <a
              key={user.did}
              href={profileUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="comic-panel interactive-panel p-4 flex flex-col h-full"
            >
              <div className="flex items-center space-x-3">
                {user.avatar ? (
                  <Image
                    src={user.avatar}
                    alt={isInvalidHandle ? 'Invalid Handle' : user.handle}
                    width={48}
                    height={48}
                    className="w-12 h-12 rounded-full border-3 border-black"
                    style={{border: '3px solid #000'}}
                    unoptimized={!user.avatar.includes('cdn.bsky.app')}
                  />
                ) : (
                  <div
                    className={`w-12 h-12 rounded-full flex items-center justify-center text-white font-bold border-3 border-black ${colors[index % colors.length]}`}
                    style={{border: '3px solid #000'}}
                  >
                    <span className="text-xl">{avatarInitial}</span>
                  </div>
                )}
                <div className="overflow-hidden flex-1">
                  <p className="text-sm font-bold text-black truncate flex items-center gap-1">
                    <span>{user.displayName || user.handle}</span>
                    {!isInvalidHandle &&
                      user.verified &&
                      (user.trustedVerifier ? (
                        <svg className="w-3.5 h-3.5 flex-shrink-0" fill="none" viewBox="0 0 24 24">
                          <path
                            fill="#1185FE"
                            d="M8.792 1.615a4.154 4.154 0 0 1 6.416 0 4.15 4.15 0 0 0 3.146 1.515 4.154 4.154 0 0 1 4 5.017 4.15 4.15 0 0 0 .777 3.404 4.154 4.154 0 0 1-1.427 6.255 4.15 4.15 0 0 0-2.177 2.73 4.154 4.154 0 0 1-5.781 2.784 4.15 4.15 0 0 0-3.492 0 4.154 4.154 0 0 1-5.78-2.784 4.15 4.15 0 0 0-2.178-2.73A4.154 4.154 0 0 1 .87 11.551a4.15 4.15 0 0 0 .776-3.404 4.154 4.154 0 0 1 4-5.017 4.15 4.15 0 0 0 3.146-1.515Z"
                          />
                          <path
                            fill="#fff"
                            fillRule="evenodd"
                            d="M17.861 8.26a1.44 1.44 0 0 1 0 2.033l-6.571 6.571a1.437 1.437 0 0 1-2.033 0L5.97 13.58a1.438 1.438 0 0 1 2.033-2.033l2.27 2.269 5.554-5.555a1.437 1.437 0 0 1 2.033 0Z"
                            clipRule="evenodd"
                          />
                        </svg>
                      ) : (
                        <svg className="w-3.5 h-3.5 flex-shrink-0" fill="none" viewBox="0 0 24 24">
                          <circle cx="12" cy="12" r="11.5" fill="#1183FE" />
                          <path
                            fill="#fff"
                            fillRule="evenodd"
                            d="M17.659 8.175a1.36 1.36 0 0 1 0 1.925l-6.224 6.223a1.36 1.36 0 0 1-1.925 0L6.4 13.212a1.361 1.361 0 0 1 1.925-1.925l2.149 2.148 5.26-5.26a1.36 1.36 0 0 1 1.925 0Z"
                            clipRule="evenodd"
                          />
                        </svg>
                      ))}
                  </p>
                  <p className="text-xs text-zinc-600 truncate">
                    {isInvalidHandle ? '⚠️ Invalid Handle' : `@${user.handle}`}
                  </p>
                </div>
              </div>
            </a>
          );
        })}
      </div>

      {hasMore && (
        <div className="flex justify-center">
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="comic-button bg-white px-6 py-2 flex items-center gap-2 hover:bg-zinc-50"
          >
            {isExpanded ? (
              <>
                <span>Show Less</span>
                <ChevronUpIcon className="w-5 h-5" />
              </>
            ) : (
              <>
                <span>Show All Users ({users.length})</span>
                <ChevronDownIcon className="w-5 h-5" />
              </>
            )}
          </button>
        </div>
      )}
    </div>
  );
}
