import { useSearch } from '@tanstack/react-router';
import { useQuery } from '@tanstack/react-query';
import { Search } from 'lucide-react';
import { api } from '@/api/client';
import { useUI } from '@/store/ui';
import { MessageReader } from '@/components/MessageReader';
import { cn, formatDate, senderName } from '@/lib/utils';

export function SearchView() {
  const { q } = useSearch({ from: '/search' }) as { q?: string };
  const { accountId, selectedThreadId, selectThread } = useUI();

  const { data, isPending } = useQuery({
    queryKey: ['search', accountId, q],
    queryFn: () => api.search(accountId!, q!),
    enabled: !!accountId && !!q,
  });

  const results = data?.results ?? [];

  return (
    <div className="flex h-full overflow-hidden">
      <div className={cn(
        'flex-none border-r border-gmail-border overflow-y-auto flex flex-col',
        selectedThreadId ? 'w-80' : 'flex-1'
      )}>
        <div className="px-6 py-3 border-b border-gmail-border text-mail-sm text-gmail-text-secondary">
          {isPending ? 'Searching…' : `${results.length} result${results.length !== 1 ? 's' : ''} for "${q}"`}
        </div>
        {results.map((msg) => (
          <button
            key={msg.id}
            onClick={() => selectThread(msg.thread_id!)}
            className={cn(
              'flex items-start gap-3 px-4 py-3 border-b border-gmail-border/40 text-left w-full',
              'hover:bg-gmail-hover transition-colors',
              selectedThreadId === msg.thread_id && 'bg-gmail-selected'
            )}
          >
            <div className="flex-1 min-w-0">
              <div className="flex items-baseline justify-between gap-2">
                <span className="font-medium text-mail-base text-gmail-text-primary truncate">
                  {senderName(msg.from_addr)}
                </span>
                <span className="text-mail-sm text-gmail-text-muted flex-none">
                  {formatDate(msg.date_sent)}
                </span>
              </div>
              <p className="text-mail-base text-gmail-text-primary truncate">{msg.subject}</p>
              <p className="text-mail-sm text-gmail-text-muted truncate">{msg.snippet}</p>
            </div>
          </button>
        ))}
        {!isPending && !results.length && q && (
          <div className="flex flex-col items-center justify-center flex-1 gap-2 text-gmail-text-secondary py-16">
            <Search size={40} className="opacity-30" />
            <p>No results for "{q}"</p>
          </div>
        )}
      </div>

      {selectedThreadId && (
        <div className="flex-1 min-w-0 overflow-hidden">
          <MessageReader threadId={selectedThreadId} />
        </div>
      )}
    </div>
  );
}
