'use client';

import { useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';

interface ConnectionCardProps {
  id: string;
  name: string;
  avatar: string;
  email: string;
  connectedAt?: string;
  onMessage?: (id: string) => void;
}

// Format date
function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

export function ConnectionCard({
  id,
  name,
  avatar,
  email,
  connectedAt,
  onMessage,
}: ConnectionCardProps) {
  const [avatarLoaded, setAvatarLoaded] = useState(false);
  const placeholder = '/assets/icons/user-placeholder-icon.svg';
  const isPlaceholder = !avatar || avatar === placeholder;

  return (
    <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 py-4">
      {/* Avatar */}
      <div className="flex-shrink-0">
        <div className="w-[80px] h-[80px] rounded-full overflow-hidden relative">
          {(!avatar || !avatarLoaded || isPlaceholder) && (
            <div className="absolute inset-0 rounded-full shimmer-loading" />
          )}
          {avatar && !isPlaceholder && (
            <img
              ref={(el) => { if (el?.complete && el.naturalWidth > 0) setAvatarLoaded(true); }}
              src={avatar}
              alt={name}
              className={`absolute inset-0 w-full h-full object-cover rounded-full transition-opacity duration-300 ${avatarLoaded ? 'opacity-100' : 'opacity-0'}`}
              onLoad={() => setAvatarLoaded(true)}
            />
          )}
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0">
        {/* Name */}
        <h3 className="font-serif font-bold text-[14px] leading-[19px] text-[#00293D] mb-1">
          {name}
        </h3>

        {/* Email */}
        <p className="font-serif font-normal text-[13px] leading-[18px] text-[#00293D]/70 mb-1">
          {email}
        </p>

        {/* Connected date */}
        {connectedAt && (
          <p className="font-serif font-normal text-[12px] text-[#00293D]/50">
            Connected on {formatDate(connectedAt)}
          </p>
        )}
      </div>

      {/* Action Buttons */}
      <div className="flex items-center gap-3 flex-shrink-0">
        <button
          onClick={() => onMessage?.(id)}
          className="h-[27px] px-4 rounded-[15px] bg-[#e58625] font-fractul font-medium text-[14px] text-[#00293D] hover:bg-[#d47920] transition-colors cursor-pointer flex items-center gap-2"
        >
          <Image
            src="/assets/icons/message-dark-icon.svg"
            alt="Message"
            width={14}
            height={13}
          />
          Message
        </button>
      </div>
    </div>
  );
}
