import { useQuery } from '@tanstack/react-query';
import {
  ArrowLeft, Archive, Trash2, MailOpen, Clock, FolderInput,
  Tag, MoreVertical, ChevronLeft, ChevronRight, Printer, AlertOctagon,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { api } from '@/api/client';
import { useUI } from '@/store/ui';
import { MessageCard } from './MessageCard';
import { queueMutation } from '@/sync/engine';

type Props = { threadId: string };

export function MessageReader({ threadId }: Props) {
  const { accountId, selectThread } = useUI();

  const { data, isPending } = useQuery({
    queryKey: ['messages', threadId],
    queryFn: () => api.messages.inThread(threadId),
    enabled: !!threadId,
  });

  const messages = data?.messages ?? [];
  const subject = messages[0]?.subject ?? '(no subject)';

  function handleArchive() {
    if (!accountId) return;
    queueMutation(accountId, 'move', threadId, { folder_special_use: 'archive' });
    selectThread(null);
  }

  function handleDelete() {
    if (!accountId) return;
    queueMutation(accountId, 'move', threadId, { folder_special_use: 'trash' });
    selectThread(null);
  }

  function handleMarkUnread() {
    if (!accountId) return;
    queueMutation(accountId, 'flag', threadId, { seen: false });
  }

  return (
    <AnimatePresence mode="wait">
      <motion.div
        key={threadId}
        initial={{ opacity: 0, y: 4 }}
        animate={{ opacity: 1, y: 0 }}
        exit={{ opacity: 0 }}
        transition={{ duration: 0.12 }}
        className="flex flex-col h-full overflow-hidden bg-white"
      >
        {/* Thread toolbar */}
        <div className="flex-none flex items-center h-12 px-2 border-b border-gmail-border">
          <ToolbarIcon onClick={() => selectThread(null)} title="Back to inbox (u)">
            <ArrowLeft size={18} />
          </ToolbarIcon>

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

          <ToolbarIcon onClick={handleArchive} title="Archive (e)">
            <Archive size={18} />
          </ToolbarIcon>
          <ToolbarIcon onClick={() => {}} title="Report spam (!)">
            <AlertOctagon size={18} />
          </ToolbarIcon>
          <ToolbarIcon onClick={handleDelete} title="Delete (#)">
            <Trash2 size={18} />
          </ToolbarIcon>

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

          <ToolbarIcon onClick={handleMarkUnread} title="Mark as unread (Shift+U)">
            <MailOpen size={18} />
          </ToolbarIcon>
          <ToolbarIcon onClick={() => {}} title="Snooze (b)">
            <Clock size={18} />
          </ToolbarIcon>
          <ToolbarIcon onClick={() => {}} title="Move to (v)">
            <FolderInput size={18} />
          </ToolbarIcon>
          <ToolbarIcon onClick={() => {}} title="Labels (l)">
            <Tag size={18} />
          </ToolbarIcon>
          <ToolbarIcon onClick={() => {}} title="More">
            <MoreVertical size={18} />
          </ToolbarIcon>

          <div className="flex-1" />

          <span className="text-mail-sm text-gmail-text-secondary pr-1 whitespace-nowrap">
            {messages.length > 0 ? `${messages.length} message${messages.length !== 1 ? 's' : ''}` : ''}
          </span>
          <ToolbarIcon onClick={() => {}} title="Newer (k)">
            <ChevronLeft size={18} />
          </ToolbarIcon>
          <ToolbarIcon onClick={() => {}} title="Older (j)">
            <ChevronRight size={18} />
          </ToolbarIcon>
          <ToolbarIcon onClick={() => window.print()} title="Print (p)">
            <Printer size={18} />
          </ToolbarIcon>
        </div>

        {/* Thread content */}
        <div className="flex-1 overflow-y-auto">
          <div className="max-w-[960px] mx-auto px-10 pt-6 pb-16">
            {/* Subject row */}
            <div className="flex items-center gap-3 pb-6">
              <h1 className="text-[22px] leading-tight text-gmail-text-primary font-normal flex-1 min-w-0 break-words">
                {subject}
              </h1>
              <span className="text-mail-sm text-gmail-text-secondary whitespace-nowrap">
                Inbox
              </span>
            </div>

            {isPending ? (
              <MessagesSkeleton />
            ) : (
              <div className="flex flex-col gap-2">
                {messages.map((msg, i) => (
                  <MessageCard
                    key={msg.id}
                    message={msg}
                    isLast={i === messages.length - 1}
                    defaultExpanded={i === messages.length - 1}
                  />
                ))}
              </div>
            )}
          </div>
        </div>
      </motion.div>
    </AnimatePresence>
  );
}

function ToolbarIcon({
  onClick, title, children,
}: { onClick: () => void; title: string; children: React.ReactNode }) {
  return (
    <button
      onClick={onClick}
      title={title}
      className="w-9 h-9 flex items-center justify-center rounded-full text-gmail-text-secondary hover:bg-black/5 hover:text-gmail-text-primary transition-colors"
    >
      {children}
    </button>
  );
}

function MessagesSkeleton() {
  return (
    <div className="flex flex-col gap-2">
      {Array.from({ length: 3 }).map((_, i) => (
        <div key={i} className="rounded-lg border border-gmail-border p-4 animate-pulse">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-full bg-gray-200 flex-none" />
            <div className="flex-1">
              <div className="h-3 w-32 bg-gray-200 rounded mb-2" />
              <div className="h-2.5 w-64 bg-gray-100 rounded" />
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
