'use client';

/**
 * Message action toolbar (reply, copy, more menu).
 */

import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { COMMON_EMOJIS } from '../shared';
import { SmilePlus, Reply as ReplyIcon, Copy, MoreHorizontal, MessageSquare, History, Edit2, Trash2 } from 'lucide-react';
import type { MessageWithMeta } from '@/contexts';
import { useCallback, useState } from 'react';
import { toast } from 'sonner';

const QUICK_EMOJIS = ['👍', '❤️', '😂', '🎉', '😮'];

interface MessageActionsProps {
  message: MessageWithMeta;
  isOwner: boolean;
  onReply?: (message: MessageWithMeta) => void;
  onCreateThread?: (message: MessageWithMeta) => void;
  onViewHistory?: (message: MessageWithMeta) => void;
  onStartEdit?: () => void;
  onRevoke?: (message: MessageWithMeta) => void;
  onReaction: (emoji: string) => void;
}

export function MessageActions({
  message,
  isOwner,
  onReply,
  onCreateThread,
  onViewHistory,
  onStartEdit,
  onRevoke,
  onReaction,
}: MessageActionsProps) {
  const [reactionPickerOpen, setReactionPickerOpen] = useState(false);

  const handleReaction = useCallback((emoji: string) => {
    onReaction(emoji);
    setReactionPickerOpen(false);
  }, [onReaction]);

  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(message.content);
      toast.success('Message copied');
    } catch {
      toast.error('Failed to copy');
    }
  }, [message.content]);

  return (
    <div className="flex items-start gap-0.5 opacity-0 transition-opacity group-hover:opacity-100">
      {/* Quick reaction bar — Slack-style hover reveal */}
      {QUICK_EMOJIS.map((emoji) => {
        const reacted = message.reactions?.find((r) => r.emoji === emoji)?.reacted_by_me;
        return (
          <Button
            key={emoji}
            variant="ghost"
            size="sm"
            onClick={() => handleReaction(emoji)}
            className={`size-6 p-0 text-sm hover:bg-accent transition-transform hover:scale-125 ${
              reacted ? 'bg-accent' : ''
            }`}
            title={emoji}
          >
            {emoji}
          </Button>
        );
      })}

      {/* Add more reaction — opens full picker */}
      <Popover open={reactionPickerOpen} onOpenChange={setReactionPickerOpen}>
        <PopoverTrigger
          render={
            <Button
              variant="ghost"
              size="sm"
              className="size-7 p-0 text-muted-foreground hover:bg-accent hover:text-foreground"
              title="Add reaction"
            >
              <SmilePlus className="size-3.5" />
            </Button>
          }
        />
        <PopoverContent className="w-auto p-2" align="start" sideOffset={4}>
          <p className="mb-2 text-xs font-medium text-muted-foreground">Select emoji</p>
          <div className="grid grid-cols-8 gap-1">
            {COMMON_EMOJIS.map((emoji) => (
              <Button
                key={emoji}
                variant="ghost"
                size="sm"
                onClick={() => handleReaction(emoji)}
                className="size-7 p-0 text-base hover:bg-accent"
                title={emoji}
              >
                {emoji}
              </Button>
            ))}
          </div>
        </PopoverContent>
      </Popover>

      {/* Reply */}
      {onReply && (
        <Button
          variant="ghost"
          size="sm"
          className="size-7 p-0 text-muted-foreground hover:bg-accent hover:text-foreground"
          onClick={() => onReply(message)}
          title="Reply"
        >
          <ReplyIcon className="size-3.5" />
        </Button>
      )}

      {/* Copy */}
      {message.content_type === 'text' && (
        <Button
          variant="ghost"
          size="sm"
          className="size-7 p-0 text-muted-foreground hover:bg-accent hover:text-foreground"
          onClick={handleCopy}
          title="Copy"
        >
          <Copy className="size-3.5" />
        </Button>
      )}

      {/* More menu */}
      <DropdownMenu>
        <DropdownMenuTrigger
          render={
            <Button
              variant="ghost"
              size="sm"
              className="size-7 p-0 text-muted-foreground hover:bg-accent hover:text-foreground"
              title="More"
            >
              <MoreHorizontal className="size-3.5" />
            </Button>
          }
        />
        <DropdownMenuContent align="end">
          {onCreateThread && !message.thread_id && (
            <DropdownMenuItem onClick={() => onCreateThread(message)}>
              <MessageSquare className="mr-2 size-4" />
              Create thread
            </DropdownMenuItem>
          )}
          {message.edited_at && onViewHistory && (
            <DropdownMenuItem onClick={() => onViewHistory(message)}>
              <History className="mr-2 size-4" />
              View edit history
            </DropdownMenuItem>
          )}
          {isOwner && message.content_type === 'text' && onStartEdit && (
            <DropdownMenuItem onClick={onStartEdit}>
              <Edit2 className="mr-2 size-4" />
              Edit
            </DropdownMenuItem>
          )}
          {isOwner && onRevoke && (
            <DropdownMenuItem onClick={() => onRevoke(message)} className="text-destructive focus:text-destructive">
              <Trash2 className="mr-2 size-4" />
              Delete
            </DropdownMenuItem>
          )}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}
