import { useState } from 'react';
import { ChevronDown, ChevronRight, Copy, Check, Share2, RotateCw } from 'lucide-react';
import { toast } from 'sonner';
import type { Chat, Message } from '@/api/types';
import { api } from '@/api/client';

export function CompactCard({ message, sessionChats }: { message: Message; sessionChats?: Chat[] }) {
  const [expanded, setExpanded] = useState(false);
  const [copied, setCopied] = useState(false);
  const [shareOpen, setShareOpen] = useState(false);
  const [rerunning, setRerunning] = useState(false);

  const headerMatch = message.content.match(/^\[Context compacted — (\d+) messages summarized\]/);
  const headerText = headerMatch ? headerMatch[0] : 'Context compacted';
  const summaryText = headerMatch
    ? message.content.slice(headerMatch[0].length).trim()
    : message.content;

  async function handleCopy() {
    try {
      await navigator.clipboard.writeText(summaryText);
      setCopied(true);
      setTimeout(() => setCopied(false), 1200);
      toast.success('Summary copied to clipboard');
    } catch {
      toast.error('Copy failed');
    }
  }

  async function handleShareToChat(chat: Chat) {
    try {
      await api.messages.send(chat.id, summaryText);
      toast.success(`Summary sent to ${chat.name ?? 'New chat'}`);
      setShareOpen(false);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Failed to share');
    }
  }

  async function handleRerun() {
    if (rerunning) return;
    setRerunning(true);
    try {
      await api.chats.compact(message.chat_id);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Re-run failed');
    } finally {
      setRerunning(false);
    }
  }

  const otherChats = (sessionChats ?? []).filter(
    (c) => c.id !== message.chat_id && c.status === 'open'
  );

  return (
    <div className="rounded-lg border bg-muted/30 text-sm">
      <div className="flex items-center gap-2 px-3 py-2">
        <button
          type="button"
          onClick={() => setExpanded(!expanded)}
          className="flex items-center gap-1.5 flex-1 min-w-0 text-left text-muted-foreground hover:text-foreground"
        >
          {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
          <span className="text-xs font-medium truncate">{headerText}</span>
        </button>
        <button
          type="button"
          onClick={() => void handleCopy()}
          className="p-1 rounded hover:bg-muted text-muted-foreground"
          aria-label="Copy summary"
          title="Copy summary"
        >
          {copied ? <Check size={12} /> : <Copy size={12} />}
        </button>
        <div className="relative">
          <button
            type="button"
            onClick={() => setShareOpen(!shareOpen)}
            className="p-1 rounded hover:bg-muted text-muted-foreground"
            aria-label="Send to chat"
            title="Send to chat"
          >
            <Share2 size={12} />
          </button>
          {shareOpen && (
            <div className="absolute right-0 top-full mt-1 z-50 bg-popover border rounded-md shadow-md min-w-[180px] py-1">
              {otherChats.length === 0 ? (
                <div className="px-3 py-1.5 text-xs text-muted-foreground">
                  No other chats in this session
                </div>
              ) : (
                otherChats.map((c) => (
                  <button
                    key={c.id}
                    type="button"
                    onClick={() => void handleShareToChat(c)}
                    className="w-full text-left px-3 py-1.5 text-xs hover:bg-accent truncate"
                  >
                    {c.name ?? 'New chat'}
                  </button>
                ))
              )}
            </div>
          )}
        </div>
        <button
          type="button"
          onClick={() => void handleRerun()}
          disabled={rerunning}
          className="p-1 rounded hover:bg-muted text-muted-foreground disabled:opacity-40"
          aria-label="Re-run compact"
          title="Re-run compact"
        >
          <RotateCw size={12} className={rerunning ? 'animate-spin' : ''} />
        </button>
      </div>
      {expanded && (
        <div className="px-3 pb-3 text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap border-t pt-2">
          {summaryText}
        </div>
      )}
    </div>
  );
}
