'use client';

import * as React from 'react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/features/shared/components/ui/dropdown-menu';
import { cn } from '@/shared/lib/utils';
import { useTranslations } from 'next-intl';

/**
 * EN: Message role type
 * VI: Kiểu vai trò của message
 */
export type MessageRole = 'user' | 'ai' | 'system';

/**
 * EN: Message feedback type
 * VI: Kiểu feedback của message
 */
export type MessageFeedback = 'like' | 'dislike' | null;

/**
 * EN: MessageActionsMenu component props
 * VI: Props của component MessageActionsMenu
 */
export interface MessageActionsMenuProps {
  /** EN: Message role (user/ai/system) / VI: Vai trò của message (user/ai/system) */
  role: MessageRole;
  /** EN: Message content to copy / VI: Nội dung message để copy */
  messageContent: string;
  /** EN: Current feedback state / VI: Trạng thái feedback hiện tại */
  feedback?: MessageFeedback;
  /** EN: Callback when copy action is triggered / VI: Callback khi action copy được kích hoạt */
  onCopy?: () => void;
  /** EN: Callback when edit action is triggered / VI: Callback khi action edit được kích hoạt */
  onEdit?: () => void;
  /** EN: Callback when delete action is triggered / VI: Callback khi action delete được kích hoạt */
  onDelete?: () => void;
  /** EN: Callback when regenerate action is triggered / VI: Callback khi action regenerate được kích hoạt */
  onRegenerate?: () => void;
  /** EN: Callback when like action is triggered / VI: Callback khi action like được kích hoạt */
  onLike?: () => void;
  /** EN: Callback when dislike action is triggered / VI: Callback khi action dislike được kích hoạt */
  onDislike?: () => void;
  /** EN: Callback when share action is triggered / VI: Callback khi action share được kích hoạt */
  onShare?: () => void;
  /** EN: Additional CSS classes / VI: Các class CSS bổ sung */
  className?: string;
  /** EN: Trigger element / VI: Element trigger */
  children?: React.ReactNode;
}

/**
 * EN: MessageActionsMenu component - Dropdown menu with message actions (copy, edit, delete, regenerate, like/dislike, share)
 * VI: Component MessageActionsMenu - Dropdown menu với các action cho message (copy, edit, delete, regenerate, like/dislike, share)
 *
 * Features:
 * - Copy message (all messages)
 * - Edit (user messages only)
 * - Delete (user messages only)
 * - Regenerate (AI messages only)
 * - Like/Dislike (feedback - all messages)
 * - Share (all messages)
 *
 * Tính năng:
 * - Copy message (tất cả messages)
 * - Edit (chỉ user messages)
 * - Delete (chỉ user messages)
 * - Regenerate (chỉ AI messages)
 * - Like/Dislike (feedback - tất cả messages)
 * - Share (tất cả messages)
 */
export function MessageActionsMenu({
  role,
  messageContent,
  feedback,
  onCopy,
  onEdit,
  onDelete,
  onRegenerate,
  onLike,
  onDislike,
  onShare,
  className,
  children,
}: MessageActionsMenuProps) {
  // EN: Translation hook / VI: Hook translation
  const t = useTranslations();

  // EN: Copy to clipboard handler / VI: Handler copy vào clipboard
  const handleCopy = React.useCallback(async () => {
    try {
      await navigator.clipboard.writeText(messageContent);
      onCopy?.();
    } catch (error) {
      console.error('Failed to copy message:', error);
    }
  }, [messageContent, onCopy]);

  // EN: Share handler using Web Share API / VI: Handler share sử dụng Web Share API
  const handleShare = React.useCallback(async () => {
    try {
      if (navigator.share) {
        await navigator.share({
          text: messageContent,
          title: t('chat.shareMessage'),
        });
        onShare?.();
      } else {
        // EN: Fallback to copy if share API is not available / VI: Fallback về copy nếu Share API không khả dụng
        await handleCopy();
        onShare?.();
      }
    } catch (error) {
      // EN: User cancelled share or error occurred / VI: User hủy share hoặc có lỗi
      if ((error as Error).name !== 'AbortError') {
        console.error('Failed to share message:', error);
      }
    }
  }, [messageContent, handleCopy, onShare]);

  // EN: Determine if message is from user / VI: Xác định message có phải từ user không
  const isUserMessage = role === 'user';

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild className={className}>
        {children || (
          <button
            className={cn(
              // EN: Base button styles - visible on hover / VI: Styles button cơ bản - hiển thị khi hover
              'opacity-0 group-hover:opacity-100 transition-opacity duration-[150ms]',
              'p-1.5 rounded-md hover:bg-bg-tertiary',
              'text-text-tertiary hover:text-text-primary',
              'focus:outline-none focus:ring-2 focus:ring-accent-primary focus:ring-offset-2'
            )}
            aria-label={t('chat.messageActions', { defaultValue: 'Message actions' })}
          >
            {/* EN: More options icon (three dots) / VI: Icon thêm tùy chọn (ba chấm) */}
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="h-4 w-4"
            >
              <circle cx="12" cy="12" r="1" />
              <circle cx="19" cy="12" r="1" />
              <circle cx="5" cy="12" r="1" />
            </svg>
          </button>
        )}
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-48">
        {/* EN: Copy action - available for all messages / VI: Action Copy - có sẵn cho tất cả messages */}
        <DropdownMenuItem onClick={handleCopy}>
          {/* EN: Copy icon / VI: Icon copy */}
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            className="mr-2 h-4 w-4"
          >
            <rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
            <path d="M4 16c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2h8c1.1 0 2 .9 2 2" />
          </svg>
          {t('chat.copy')}
        </DropdownMenuItem>

        {/* EN: Edit action - only for user messages / VI: Action Edit - chỉ cho user messages */}
        {isUserMessage && onEdit && (
          <DropdownMenuItem onClick={onEdit}>
            {/* EN: Edit icon / VI: Icon edit */}
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="mr-2 h-4 w-4"
            >
              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
              <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
            </svg>
            {t('chat.edit')}
          </DropdownMenuItem>
        )}

        {/* EN: Regenerate action - only for AI messages / VI: Action Regenerate - chỉ cho AI messages */}
        {!isUserMessage && onRegenerate && (
          <DropdownMenuItem onClick={onRegenerate}>
            {/* EN: Refresh/Regenerate icon / VI: Icon refresh/regenerate */}
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="mr-2 h-4 w-4"
            >
              <path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" />
              <path d="M21 3v5h-5" />
              <path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" />
              <path d="M8 16H3v5" />
            </svg>
            {t('chat.regenerate')}
          </DropdownMenuItem>
        )}

        <DropdownMenuSeparator />

        {/* EN: Like/Dislike actions - available for all messages / VI: Actions Like/Dislike - có sẵn cho tất cả messages */}
        {onLike && (
          <DropdownMenuItem
            onClick={onLike}
            className={cn(feedback === 'like' && 'bg-bg-tertiary')}
          >
            {/* EN: Like icon (thumbs up) / VI: Icon like (thumbs up) */}
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill={feedback === 'like' ? 'currentColor' : 'none'}
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="mr-2 h-4 w-4"
            >
              <path d="M7 10v12" />
              <path d="M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2h0a3.13 3.13 0 0 1 3 3.88Z" />
            </svg>
            {t('chat.like')}
          </DropdownMenuItem>
        )}

        {onDislike && (
          <DropdownMenuItem
            onClick={onDislike}
            className={cn(feedback === 'dislike' && 'bg-bg-tertiary')}
          >
            {/* EN: Dislike icon (thumbs down) / VI: Icon dislike (thumbs down) */}
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill={feedback === 'dislike' ? 'currentColor' : 'none'}
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="mr-2 h-4 w-4"
            >
              <path d="M17 14V2" />
              <path d="M9 18.12 10 14H4.17a2 2 0 0 0-1.92 2.56l2.33 8A2 2 0 0 0 6.5 22H20a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2h-2.76a2 2 0 0 0-1.79-1.11L12 2h0a3.13 3.13 0 0 0-3 3.88Z" />
            </svg>
            {t('chat.dislike')}
          </DropdownMenuItem>
        )}

        {/* EN: Share action - available for all messages / VI: Action Share - có sẵn cho tất cả messages */}
        {onShare && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem onClick={handleShare}>
              {/* EN: Share icon / VI: Icon share */}
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="mr-2 h-4 w-4"
              >
                <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
                <polyline points="16 6 12 2 8 6" />
                <line x1="12" x2="12" y1="2" y2="15" />
              </svg>
              {t('chat.share')}
            </DropdownMenuItem>
          </>
        )}

        {/* EN: Delete action - only for user messages / VI: Action Delete - chỉ cho user messages */}
        {isUserMessage && onDelete && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onClick={onDelete}
              className="text-accent-error focus:text-accent-error focus:bg-bg-tertiary"
            >
              {/* EN: Delete icon / VI: Icon delete */}
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="mr-2 h-4 w-4"
              >
                <path d="M3 6h18" />
                <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
                <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
              </svg>
              {t('chat.delete')}
            </DropdownMenuItem>
          </>
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
