'use client';

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

// Helper to get a valid avatar URL
function getValidAvatarUrl(avatar: string | null | undefined): string {
  const placeholder = '/assets/icons/user-placeholder-icon.svg';
  if (!avatar) return placeholder;
  if (avatar.startsWith('http://') || avatar.startsWith('https://') || avatar.startsWith('/')) {
    return avatar;
  }
  return placeholder;
}

export interface ConnectedContact {
  id: string; // agentProfileId (for users) or userId (for agents)
  name: string;
  avatar: string | null;
  avatarUrl: string | null;
  headline: string | null;
  email: string | null;
  city: string | null;
  state: string | null;
}

interface NewConversationModalProps {
  isOpen: boolean;
  onClose: () => void;
  contacts: ConnectedContact[];
  isLoading: boolean;
  onStartConversation: (contactId: string) => Promise<void>;
}

export function NewConversationModal({
  isOpen,
  onClose,
  contacts,
  isLoading,
  onStartConversation,
}: NewConversationModalProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [startingId, setStartingId] = useState<string | null>(null);

  if (!isOpen) return null;

  const filteredContacts = contacts.filter((contact) =>
    contact.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleStart = async (contactId: string) => {
    setStartingId(contactId);
    try {
      await onStartConversation(contactId);
      onClose();
    } catch (error) {
      console.error('Failed to start conversation:', error);
    } finally {
      setStartingId(null);
    }
  };

  return (
    <div
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="bg-white rounded-[20px] w-full max-w-[480px] mx-4 shadow-xl overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-[#00293d]/10">
          <h2 className="font-fractul font-bold text-[16px] text-[#00293D]">
            New Conversation
          </h2>
          <button
            onClick={onClose}
            className="p-1 hover:bg-gray-100 rounded-lg transition-colors cursor-pointer"
          >
            <Image
              src="/assets/icons/close-icon.svg"
              alt="Close"
              width={20}
              height={20}
            />
          </button>
        </div>

        {/* Search */}
        <div className="p-4 border-b border-[#00293d]/10">
          <div className="flex items-center gap-2 border border-[#00293d]/10 rounded-[15px] px-4 py-2">
            <Image
              src="/assets/icons/search-icon.svg"
              alt="Search"
              width={18}
              height={18}
            />
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Search connections..."
              className="flex-1 font-serif font-normal text-[14px] text-[#00293D] placeholder-[#00293D]/50 focus:outline-none"
              autoFocus
            />
          </div>
        </div>

        {/* Contact list */}
        <div className="max-h-[400px] overflow-y-auto">
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#00293d]" />
            </div>
          ) : filteredContacts.length === 0 ? (
            <div className="flex items-center justify-center py-12 px-4">
              <p className="font-serif font-normal text-[14px] text-[#00293D]/50 text-center">
                {searchQuery
                  ? 'No connections match your search'
                  : 'No connections yet'}
              </p>
            </div>
          ) : (
            <div className="p-2 space-y-1">
              {filteredContacts.map((contact) => (
                <button
                  key={contact.id}
                  onClick={() => handleStart(contact.id)}
                  disabled={startingId === contact.id}
                  className="w-full flex items-center gap-3 p-3 rounded-[12px] cursor-pointer transition-colors hover:bg-[#00293d]/5 disabled:opacity-50"
                >
                  {/* Avatar */}
                  <div className="w-[44px] h-[44px] rounded-full overflow-hidden border border-[#00293D]/20 flex-shrink-0 relative">
                    {/* Initials base layer */}
                    <div className="absolute inset-0 rounded-full bg-[#c4d9d4] flex items-center justify-center">
                      <span className="font-bold text-[#00293d] text-[18px]">{contact.name?.[0]?.toUpperCase() || '?'}</span>
                    </div>
                    {contact.avatarUrl && !contact.avatarUrl.endsWith('user-placeholder-icon.svg') && (
                      <img
                        src={getValidAvatarUrl(contact.avatarUrl)}
                        alt={contact.name}
                        className="absolute inset-0 w-full h-full object-cover"
                        onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }}
                      />
                    )}
                  </div>

                  {/* Info */}
                  <div className="flex-1 min-w-0 text-left">
                    <p className="font-fractul font-medium text-[14px] leading-[17px] text-[#00293D]">
                      {contact.name}
                    </p>
                    {contact.headline && (
                      <p className="font-serif font-normal text-[12px] leading-[16px] text-[#00293D]/70 truncate">
                        {contact.headline}
                      </p>
                    )}
                    {contact.email && !contact.headline && (
                      <p className="font-serif font-normal text-[12px] leading-[16px] text-[#00293D]/70 truncate">
                        {contact.email}
                      </p>
                    )}
                    {(contact.city || contact.state) && (
                      <p className="font-serif font-normal text-[11px] leading-[14px] text-[#00293D]/50">
                        {[contact.state, contact.city].filter(Boolean).join(', ')}
                      </p>
                    )}
                  </div>

                  {/* Loading or arrow */}
                  <div className="flex-shrink-0">
                    {startingId === contact.id ? (
                      <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[#e58625]" />
                    ) : (
                      <div className="w-8 h-8 rounded-full bg-[#e58625]/10 flex items-center justify-center">
                        <Image
                          src="/assets/icons/message-icon.svg"
                          alt="Start chat"
                          width={16}
                          height={16}
                          className="opacity-70"
                        />
                      </div>
                    )}
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
