import { useMemo, type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import type { Contact, Conversation } from '@/types';
import { normalizeHandle, rankConversationsByQuery } from './rankConversations';

const Box = styled.details`
  margin: 8px 12px;
  padding: 8px 10px;
  font-family: ui-monospace, SFMono-Regular, monospace;
  font-size: 11px;
  color: #c0c0d0;
  background: #0a0a14;
  border: 1px solid #3a3a4a;
  border-radius: 4px;

  summary {
    cursor: pointer;
    color: #c9a84c;
    font-weight: 700;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    font-size: 10px;
  }
`;

const Section = styled.div`
  margin-top: 8px;
`;

const Line = styled.div`
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
`;

const Hit = styled.div<{ $ok: boolean }>`
  color: ${({ $ok }) => ($ok ? '#7ec97e' : '#d97777')};
`;

interface SearchDiagnosticProps {
  query: string;
  conversations: readonly Conversation[];
  contacts: readonly Contact[];
  selectedConversationId: string | null;
}

export function SearchDiagnostic({
  query,
  conversations,
  contacts,
  selectedConversationId,
}: SearchDiagnosticProps): ReactElement {
  const q = query.trim().toLowerCase();

  const matchingContacts = useMemo(
    () =>
      contacts.filter((c) => {
        const n = c.displayName.toLowerCase();
        return q.length >= 2 && n.includes(q);
      }),
    [contacts, q],
  );

  const ranked = useMemo(
    () => rankConversationsByQuery(conversations, contacts, query, 25),
    [conversations, contacts, query],
  );

  const selectedHandles = useMemo(() => {
    const conv = conversations.find((c) => c.id === selectedConversationId);
    return conv?.participants ?? [];
  }, [conversations, selectedConversationId]);

  const selectedInRanked = ranked.some((r) => r.conv.id === selectedConversationId);

  return (
    <Box>
      <summary>Search diagnostic ({contacts.length} contacts · {conversations.length} convs)</summary>

      <Section>
        <Line><strong>Query:</strong> {q || '(empty)'}</Line>
      </Section>

      <Section>
        <Line><strong>Contacts matching name:</strong> {matchingContacts.length}</Line>
        {matchingContacts.length === 0 && q.length >= 2 && (
          <Hit $ok={false}>
            ⚠ No contact named like "{q}" in icloud.contacts. Either the contact
            isn't synced to this device, or her display_name differs.
          </Hit>
        )}
        {matchingContacts.map((c) => {
          const handles = [c.handle, ...c.phoneNumbers, ...c.emails]
            .filter(Boolean)
            .map((h) => `${h} → ${normalizeHandle(h)}`);
          const linked = conversations.filter((conv) =>
            conv.participants.some((p) =>
              [c.handle, ...c.phoneNumbers, ...c.emails]
                .map(normalizeHandle)
                .includes(normalizeHandle(p)),
            ),
          );
          return (
            <div key={c.id} style={{ marginTop: 6, paddingLeft: 8, borderLeft: '1px solid #2a2a3a' }}>
              <Line><strong>{c.displayName}</strong> ({c.id})</Line>
              <Line>handles: {handles.join(', ') || '(none)'}</Line>
              <Hit $ok={linked.length > 0}>
                linked conversations: {linked.length}
                {linked.length === 0 && ' ⚠ contact name matches but no conversation has any of her handles in participants'}
              </Hit>
              {linked.map((conv) => (
                <Line key={conv.id}>
                  · {conv.id} (participants: {conv.participants.join(', ')})
                </Line>
              ))}
            </div>
          );
        })}
      </Section>

      <Section>
        <Line><strong>Ranked matches:</strong> {ranked.length}</Line>
        {ranked.map((r, i) => (
          <Line key={r.conv.id}>
            #{i + 1} rank={r.rank} · {r.label} · {r.conv.id}
          </Line>
        ))}
      </Section>

      {selectedConversationId && (
        <Section>
          <Line><strong>Selected conv:</strong> {selectedConversationId}</Line>
          <Line>participants: {selectedHandles.join(', ') || '(none)'}</Line>
          <Hit $ok={selectedInRanked}>
            in ranked matches: {selectedInRanked ? 'yes' : 'no — surfaced via server-side message search only'}
          </Hit>
        </Section>
      )}
    </Box>
  );
}
