import { useEffect, useState } from 'react';
import { useQuery, useMutation } from '@apollo/client/react';
import { useNavigate } from 'react-router-dom';
import { LIST_SUMMARIES_QUERY } from '../api/operations/queries';
import { CHATS_MARK_READ_MUTATION } from '../api/operations/mutations';
import { ChatListItem } from '../components/chat/ChatListItem';
import { LoadingPage } from '../components/ui/Loading';

export function MessagesPage() {
  const navigate = useNavigate();

  const { data, loading, error } = useQuery(LIST_SUMMARIES_QUERY, {
    variables: { limit: 30 },
  });

  // Build a profileId -> discoveredLocation map from our cache
  const [locationByProfileId, setLocationByProfileId] = useState<Record<string, string>>({});
  useEffect(() => {
    fetch('/api/discovered-profiles')
      .then(r => r.ok ? r.json() : null)
      .then(d => {
        if (!d?.profiles) return;
        const map: Record<string, string> = {};
        for (const p of d.profiles) {
          if (p.id && typeof p.discoveredLocation === 'string' && p.discoveredLocation) {
            map[p.id] = p.discoveredLocation;
          }
        }
        setLocationByProfileId(map);
      })
      .catch(() => {});
  }, []);

  const [chatsMarkRead, { loading: markingRead }] = useMutation(CHATS_MARK_READ_MUTATION);

  const handleMarkAllRead = async () => {
    const chats = data?.summaries?.nodes || [];
    const chatIds = chats.map((c: any) => c.id).filter(Boolean);
    if (chatIds.length === 0) return;
    try {
      await chatsMarkRead({ variables: { input: { chatIds } } });
    } catch (err) {
      console.error('Failed to mark chats as read:', err);
    }
  };

  if (loading) return <LoadingPage message="Loading conversations..." />;

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-20 animate-fade-up">
        <div className="
          w-16 h-16 rounded-full
          bg-red-500/10
          flex items-center justify-center
          mb-6
        ">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="w-8 h-8 text-red-400">
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z" />
          </svg>
        </div>
        <h2 className="font-display text-xl font-semibold text-[var(--color-text-primary)] mb-2">
          Unable to Load Messages
        </h2>
        <p className="text-[var(--color-text-muted)] text-sm max-w-xs text-center">
          {error.message}
        </p>
      </div>
    );
  }

  const chats = data?.summaries?.nodes || [];

  if (chats.length === 0) {
    return (
      <div className="pb-8">
        {/* Header */}
        <div className="mb-8 animate-fade-up">
          <h1 className="font-display text-3xl md:text-4xl font-bold text-[var(--color-text-primary)] mb-2">
            Messages
          </h1>
          <p className="text-[var(--color-text-muted)]">
            Your conversations
          </p>
        </div>

        {/* Empty State */}
        <div className="flex flex-col items-center justify-center py-20 animate-fade-up" style={{ animationDelay: '50ms' }}>
          <div className="
            w-20 h-20 rounded-full
            bg-gradient-to-br from-[var(--color-surface-elevated)] to-[var(--color-surface)]
            flex items-center justify-center
            mb-6
          ">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" className="w-10 h-10 text-[var(--color-text-muted)]/50">
              <path strokeLinecap="round" strokeLinejoin="round" d="M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 01-2.555-.337A5.972 5.972 0 015.41 20.97a5.969 5.969 0 01-.474-.065 4.48 4.48 0 00.978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25z" />
            </svg>
          </div>
          <h2 className="font-display text-xl font-semibold text-[var(--color-text-primary)] mb-2">
            No Conversations Yet
          </h2>
          <p className="text-[var(--color-text-muted)] text-sm max-w-xs text-center">
            Match with someone to start chatting
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="pb-8">
      {/* Header */}
      <div className="mb-8 animate-fade-up flex items-start justify-between">
        <div>
          <h1 className="font-display text-3xl md:text-4xl font-bold text-[var(--color-text-primary)] mb-2">
            Messages
          </h1>
          <p className="text-[var(--color-text-muted)]">
            {chats.length} {chats.length === 1 ? 'conversation' : 'conversations'}
          </p>
        </div>
        <button
          onClick={handleMarkAllRead}
          disabled={markingRead}
          className="
            mt-1 px-4 py-2 rounded-full
            bg-white/[0.06] hover:bg-white/[0.1]
            text-sm text-[var(--color-text-muted)] hover:text-[var(--color-text-primary)]
            transition-all duration-200
            border border-white/[0.06]
            font-body
            disabled:opacity-50 disabled:cursor-not-allowed
            flex items-center gap-2
          "
        >
          {markingRead ? (
            <>
              <div className="w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
              Marking...
            </>
          ) : (
            <>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-4 h-4">
                <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
              </svg>
              Mark All Read
            </>
          )}
        </button>
      </div>

      {/* Chat List */}
      <div className="space-y-2">
        {chats.map((chat: any, index: number) => (
          <div
            key={chat.id}
            className="animate-fade-up"
            style={{ animationDelay: `${(index + 1) * 30}ms` }}
          >
            <ChatListItem
              chat={{ ...chat, discoveredLocation: locationByProfileId[chat.targetProfileId] ?? null }}
              onClick={() => {
                const params = new URLSearchParams();
                if (chat.name) params.set('name', chat.name);
                if (chat.avatarSet?.[0]) params.set('avatar', chat.avatarSet[0]);
                navigate(`/chat/${chat.streamChannelId}?${params.toString()}`);
              }}
            />
          </div>
        ))}
      </div>
    </div>
  );
}
