'use client';

import { useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useSession } from 'next-auth/react';
import { useRouter, usePathname } from 'next/navigation';
import { Tag } from './Tag';

type ConnectionStatus = 'PENDING' | 'ACCEPTED' | 'REJECTED' | null;

interface ProfileCardProps {
  firstName: string;
  lastName: string;
  isVerified: boolean;
  title: string;
  location: string;
  memberSince: string;
  bio: string;
  expertise: string[];
  showEditButton?: boolean;
  editHref?: string;
  messageHref?: string;
  requestsHref?: string;
  pendingRequestCount?: number;
  connectionStatus?: ConnectionStatus;
  onConnectClick?: () => void; // Callback when Connect button is clicked (for opening modal)
  onUnlinkClick?: () => void; // Callback when Unlink button is clicked
}

export function ProfileCard({
  firstName,
  lastName,
  isVerified,
  title,
  location,
  memberSince,
  bio,
  expertise,
  showEditButton = false,
  editHref = '/agent/edit',
  messageHref,
  requestsHref,
  pendingRequestCount = 0,
  connectionStatus,
  onConnectClick,
  onUnlinkClick,
}: ProfileCardProps) {
  const { data: session } = useSession();
  const router = useRouter();
  const pathname = usePathname();
  const [isUnlinking, setIsUnlinking] = useState(false);
  const [showLocationModal, setShowLocationModal] = useState(false);

  // Split location into parts and limit display
  const locationParts = location.split(',').map(s => s.trim()).filter(Boolean);
  const maxVisibleLocations = 4;
  const visibleLocations = locationParts.slice(0, maxVisibleLocations).join(', ');
  const hasMoreLocations = locationParts.length > maxVisibleLocations;
  const remainingCount = locationParts.length - maxVisibleLocations;

  // Handle unlink click
  const handleUnlinkClick = async () => {
    if (isUnlinking) return;
    setIsUnlinking(true);
    try {
      await onUnlinkClick?.();
    } finally {
      setIsUnlinking(false);
    }
  };

  // Handle action click - require login if not authenticated
  const handleActionClick = (e: React.MouseEvent, targetHref?: string) => {
    if (!session) {
      e.preventDefault();
      // Store the current page to redirect back after login
      const returnUrl = encodeURIComponent(pathname);
      router.push(`/login?callbackUrl=${returnUrl}`);
      return;
    }
    // If logged in and has href, navigation will happen naturally via Link
    if (!targetHref) {
      e.preventDefault();
      // Handle button click when logged in but no href specified
    }
  };

  return (
    <div className="bg-white rounded-[20px] p-4 lg:p-5">
      {/* Name and Actions Row */}
      <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4 mb-4">
        <div className="text-center lg:text-left">
          <div className="flex items-center justify-center lg:justify-start gap-2 mb-1">
            <h1 className="text-[18px] text-[#00293d] font-serif">
              <span className="font-semibold">{firstName}</span>{' '}
              <span className="font-normal">{lastName}</span>
            </h1>
            {isVerified && (
              <>
                <Image
                  src="/assets/icons/verified-icon.svg"
                  alt="Verified"
                  width={15}
                  height={14}
                />
                <span className="text-[14px] text-[#638559] font-medium font-serif">
                  (Verified Expert)
                </span>
              </>
            )}
            {showEditButton && (
              <Link href={editHref} className="p-1 hover:bg-gray-100 rounded transition-colors">
                <Image
                  src="/assets/icons/edit-pencil-orange-icon.svg"
                  alt="Edit profile"
                  width={16}
                  height={16}
                />
              </Link>
            )}
          </div>
          <p className="text-[#00293d] text-sm mb-2 font-fractul">{title}</p>
          <div className="flex flex-wrap items-center justify-center lg:justify-start gap-x-4 gap-y-1 text-sm text-[#00293d] font-fractul">
            <span className="flex items-center gap-1">
              <Image
                src="/assets/icons/location-pin-icon.svg"
                alt="Location"
                width={21}
                height={19}
                className="flex-shrink-0"
              />
              <span className="text-[14px] font-bold text-[#00293D] font-serif leading-[19px]">
                {visibleLocations}
                {hasMoreLocations && (
                  <button
                    onClick={() => setShowLocationModal(true)}
                    className="ml-1 text-[#e58625] hover:underline cursor-pointer"
                  >
                    +{remainingCount} more
                  </button>
                )}
              </span>
            </span>
            <span className="flex items-center gap-1 flex-shrink-0">
              <Image
                src="/assets/icons/calendar-icon.svg"
                alt="Calendar"
                width={23}
                height={21}
              />
              <span className="text-[13px] font-medium text-[#00293D] font-serif leading-[18px] whitespace-nowrap">
                Member Since {memberSince}
              </span>
            </span>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex items-center justify-center lg:justify-start gap-3">
          {/* Message button - only enabled when connected */}
          {(showEditButton || connectionStatus === 'ACCEPTED') && (
            messageHref ? (
              <Link
                href={messageHref}
                onClick={(e) => handleActionClick(e, messageHref)}
                className="flex items-center gap-2 px-4 py-1.5 bg-[#e58625] text-[#00293d] text-sm font-normal rounded-[15px] border border-[#00293d]/10 hover:bg-[#d47720] transition-colors font-serif cursor-pointer"
              >
                <Image
                  src="/assets/icons/message-dark-icon.svg"
                  alt="Message"
                  width={14}
                  height={13}
                />
                Message
              </Link>
            ) : (
              <button
                onClick={(e) => handleActionClick(e)}
                className="flex items-center gap-2 px-4 py-1.5 bg-[#e58625] text-[#00293d] text-sm font-normal rounded-[15px] border border-[#00293d]/10 hover:bg-[#d47720] transition-colors font-serif cursor-pointer"
              >
                <Image
                  src="/assets/icons/message-dark-icon.svg"
                  alt="Message"
                  width={14}
                  height={13}
                />
                Message
              </button>
            )
          )}
          {showEditButton && requestsHref ? (
            // Agent's own profile - show Requests link with badge
            <Link
              href={requestsHref}
              onClick={(e) => handleActionClick(e, requestsHref)}
              className="relative flex items-center gap-2 px-4 py-1.5 bg-[#e58625] text-[#00293d] text-sm font-normal rounded-[15px] border border-[#00293d]/10 hover:bg-[#d47720] transition-colors font-serif cursor-pointer"
            >
              <Image
                src="/assets/icons/requests-dark-icon.svg"
                alt="Requests"
                width={14}
                height={13}
              />
              Requests
              {pendingRequestCount > 0 && (
                <span className="absolute -top-2 -right-2 min-w-[20px] h-[20px] flex items-center justify-center px-1 bg-red-500 text-white text-[11px] font-bold rounded-full">
                  {pendingRequestCount > 99 ? '99+' : pendingRequestCount}
                </span>
              )}
            </Link>
          ) : (
            // Public view - show Connect/Pending/Unlink button based on connection status
            connectionStatus === 'PENDING' ? (
              <button
                disabled
                className="flex items-center gap-2 px-4 py-1.5 bg-[#fef3c7] text-[#92600f] text-sm font-normal rounded-[15px] border border-[#00293d]/10 cursor-not-allowed font-serif"
              >
                <Image
                  src="/assets/icons/requests-dark-icon.svg"
                  alt="Pending"
                  width={14}
                  height={13}
                />
                Pending
              </button>
            ) : connectionStatus === 'ACCEPTED' ? (
              <button
                onClick={handleUnlinkClick}
                disabled={isUnlinking}
                className="flex items-center gap-2 px-4 py-1.5 bg-red-500 text-white text-sm font-normal rounded-[15px] border border-[#00293d]/10 hover:bg-red-600 transition-colors font-serif cursor-pointer disabled:opacity-50"
              >
                <Image
                  src="/assets/icons/requests-dark-icon.svg"
                  alt="Unlink"
                  width={14}
                  height={13}
                />
                {isUnlinking ? 'Unlinking...' : 'Unlink'}
              </button>
            ) : (
              <button
                onClick={(e) => {
                  if (!session) {
                    e.preventDefault();
                    const returnUrl = encodeURIComponent(pathname);
                    router.push(`/login?callbackUrl=${returnUrl}`);
                    return;
                  }
                  onConnectClick?.();
                }}
                className="flex items-center gap-2 px-4 py-1.5 bg-[#e58625] text-[#00293d] text-sm font-normal rounded-[15px] border border-[#00293d]/10 hover:bg-[#d47720] transition-colors font-serif cursor-pointer"
              >
                <Image
                  src="/assets/icons/requests-dark-icon.svg"
                  alt="Connect"
                  width={14}
                  height={13}
                />
                Connect
              </button>
            )
          )}
        </div>
      </div>

      {/* Bio */}
      <p className="text-[14px] font-normal text-[#00293D] font-serif leading-[20px] mb-4 text-center lg:text-left">
        {bio}
      </p>

      {/* Expertise Tags */}
      <div>
        <p className="text-[14px] font-bold text-[#00293D] font-fractul leading-[17px] mb-2 text-center lg:text-left">
          Expertise:
        </p>
        {/* Separate long text entries from short tag entries */}
        {expertise.filter(tag => tag.length > 60).length > 0 && (
          <p className="text-[14px] font-normal text-[#00293D] font-serif leading-[20px] mb-2 text-center lg:text-left break-words">
            {expertise.filter(tag => tag.length > 60).join(' ')}
          </p>
        )}
        <div className="flex flex-wrap gap-2 justify-center lg:justify-start">
          {expertise.filter(tag => tag.length <= 60).map((tag, idx) => (
            <Tag key={idx}>{tag}</Tag>
          ))}
        </div>
      </div>

      {/* Location Modal */}
      {showLocationModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={() => setShowLocationModal(false)}>
          <div className="bg-white rounded-[20px] p-6 max-w-[400px] w-full max-h-[80vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-fractul font-bold text-[18px] text-[#00293D]">Service Areas</h3>
              <button
                onClick={() => setShowLocationModal(false)}
                className="text-[#00293D]/50 hover:text-[#00293D] text-[20px] leading-none cursor-pointer"
              >
                &times;
              </button>
            </div>
            <div className="flex flex-wrap gap-2">
              {locationParts.map((loc, idx) => (
                <span
                  key={idx}
                  className="px-3 py-1.5 bg-[#e8e8e8] rounded-[10px] text-[13px] font-serif text-[#00293D]"
                >
                  {loc}
                </span>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
