import { useParams } from '@tanstack/react-router';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { RefreshCw, MoreVertical, ChevronLeft, ChevronRight, ChevronDown } from 'lucide-react';
import { useUI } from '@/store/ui';
import { api } from '@/api/client';
import { ThreadList } from '@/components/ThreadList';
import { MessageReader } from '@/components/MessageReader';
import { cn } from '@/lib/utils';

const SPECIAL_USE_TO_SPECIAL = new Set(['inbox', 'sent', 'drafts', 'archive', 'trash', 'junk', 'flagged']);

export function FolderView() {
  const { folderId: folderSlug } = useParams({ from: '/f/$folderId' });
  const { accountId, selectedThreadId, checkedThreadIds, clearChecks } = useUI();
  const queryClient = useQueryClient();

  const { data: foldersData } = useQuery({
    queryKey: ['folders', accountId],
    queryFn: () => api.folders.list(accountId!),
    enabled: !!accountId,
  });

  const folders = foldersData?.folders ?? [];
  const resolved = SPECIAL_USE_TO_SPECIAL.has(folderSlug)
    ? folders.find((f) => f.special_use === folderSlug)
    : folders.find((f) => f.id === folderSlug);

  const realFolderId = resolved?.id ?? null;

  if (!realFolderId || !resolved) {
    return (
      <div className="flex items-center justify-center h-full text-gmail-text-secondary text-mail-sm">
        {foldersData ? 'Folder not found' : 'Loading…'}
      </div>
    );
  }

  const refresh = () => {
    queryClient.invalidateQueries({ queryKey: ['threads', realFolderId] });
    queryClient.invalidateQueries({ queryKey: ['folders', accountId] });
  };

  const anyChecked = checkedThreadIds.size > 0;

  return (
    <div className="flex h-full overflow-hidden bg-white">
      <div
        className={cn(
          'flex-none border-r border-gmail-border overflow-hidden flex flex-col bg-white',
          selectedThreadId ? 'w-[420px]' : 'flex-1',
          'transition-[width] duration-150',
        )}
      >
        {/* Toolbar */}
        <div className="flex-none flex items-center h-12 px-3 border-b border-gmail-border bg-white">
          {/* Select-all checkbox + caret */}
          <div className="flex items-center">
            <button
              onClick={() => (anyChecked ? clearChecks() : null)}
              className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-black/5 transition-colors"
              aria-label="Select all"
              title="Select"
            >
              <span
                className={cn(
                  'w-[18px] h-[18px] rounded-[3px] border-2 flex items-center justify-center transition-colors',
                  anyChecked
                    ? 'border-gmail-blue bg-gmail-blue'
                    : 'border-gmail-text-secondary bg-transparent',
                )}
              >
                {anyChecked && (
                  <span className="block w-2 h-0.5 bg-white rounded" />
                )}
              </span>
            </button>
            <button
              className="w-6 h-9 flex items-center justify-center rounded-full hover:bg-black/5 transition-colors"
              aria-label="Select options"
            >
              <ChevronDown size={14} className="text-gmail-text-secondary" />
            </button>
          </div>

          <div className="w-px h-5 bg-gmail-border mx-2" />

          {/* Refresh */}
          <button
            onClick={refresh}
            className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-black/5 transition-colors"
            title="Refresh"
          >
            <RefreshCw size={16} className="text-gmail-text-secondary" />
          </button>

          <button
            className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-black/5 transition-colors"
            title="More"
          >
            <MoreVertical size={16} className="text-gmail-text-secondary" />
          </button>

          <div className="flex-1" />

          {/* Counter & pager */}
          {resolved.total_count > 0 && (
            <span className="text-mail-sm text-gmail-text-secondary pr-1 whitespace-nowrap">
              1–{Math.min(50, resolved.total_count)} of {resolved.total_count.toLocaleString()}
            </span>
          )}
          <button
            className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-black/5 transition-colors"
            title="Newer"
          >
            <ChevronLeft size={16} className="text-gmail-text-secondary" />
          </button>
          <button
            className="w-9 h-9 flex items-center justify-center rounded-full hover:bg-black/5 transition-colors"
            title="Older"
          >
            <ChevronRight size={16} className="text-gmail-text-secondary" />
          </button>
        </div>

        <ThreadList folderId={realFolderId} />
      </div>

      {selectedThreadId ? (
        <div className="flex-1 min-w-0 overflow-hidden bg-white">
          <MessageReader threadId={selectedThreadId} />
        </div>
      ) : (
        <div className="hidden md:flex flex-1 items-center justify-center text-gmail-text-muted text-mail-sm">
          Select a conversation to read
        </div>
      )}
    </div>
  );
}
