'use client';

import * as React from 'react';
import { cn } from '@/shared/lib/utils';
import { Avatar, AvatarFallback, AvatarImage } from '@/features/shared/components/ui/avatar';
import { useTranslations } from 'next-intl';
import { useI18n } from '@/features/theme';

/**
 * EN: Message sender type
 * VI: Loại người gửi tin nhắn
 */
export type MessageSender = 'user' | 'ai' | 'system';

/**
 * EN: Message bubble props interface
 * VI: Interface cho props của component Message bubble
 */
export interface MessageBubbleProps {
  /**
   * EN: Message sender type (user, ai, or system)
   * VI: Loại người gửi tin nhắn (user, ai, hoặc system)
   */
  sender: MessageSender;
  /**
   * EN: Message content / VI: Nội dung tin nhắn
   */
  content: string;
  /**
   * EN: Message timestamp / VI: Thời gian tin nhắn
   */
  timestamp?: Date | string;
  /**
   * EN: Author name / VI: Tên tác giả
   */
  authorName?: string;
  /**
   * EN: Author avatar URL / VI: URL avatar tác giả
   */
  authorAvatar?: string;
  /**
   * EN: Whether to show message actions on hover
   * VI: Có hiển thị các hành động tin nhắn khi hover không
   */
  showActions?: boolean;
  /**
   * EN: Callback when copy action is clicked
   * VI: Callback khi hành động copy được click
   */
  onCopy?: () => void;
  /**
   * EN: Callback when edit action is clicked (user messages only)
   * VI: Callback khi hành động edit được click (chỉ tin nhắn user)
   */
  onEdit?: () => void;
  /**
   * EN: Callback when delete action is clicked (user messages only)
   * VI: Callback khi hành động delete được click (chỉ tin nhắn user)
   */
  onDelete?: () => void;
  /**
   * EN: Callback when regenerate action is clicked (AI messages only)
   * VI: Callback khi hành động regenerate được click (chỉ tin nhắn AI)
   */
  onRegenerate?: () => void;
  /**
   * EN: Callback when like action is clicked
   * VI: Callback khi hành động like được click
   */
  onLike?: () => void;
  /**
   * EN: Callback when dislike action is clicked
   * VI: Callback khi hành động dislike được click
   */
  onDislike?: () => void;
  /**
   * EN: Callback when share action is clicked
   * VI: Callback khi hành động share được click
   */
  onShare?: () => void;
  /**
   * EN: Whether the message is liked
   * VI: Tin nhắn có được like không
   */
  isLiked?: boolean;
  /**
   * EN: Whether the message is disliked
   * VI: Tin nhắn có được dislike không
   */
  isDisliked?: boolean;
  /**
   * EN: Additional CSS classes
   * VI: Các class CSS bổ sung
   */
  className?: string;
}

/**
 * EN: Format timestamp to readable string
 * VI: Format timestamp thành chuỗi dễ đọc
 */
function formatTimestamp(timestamp: Date | string, t: (key: string, values?: any) => string, locale: string): string {
  const date = typeof timestamp === 'string' ? new Date(timestamp) : timestamp;
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  if (diffMins < 1) {
    return t('chat.justNow');
  } else if (diffMins < 60) {
    return t('chat.minutesAgo', { minutes: diffMins });
  } else if (diffHours < 24) {
    return t('chat.hoursAgo', { hours: diffHours });
  } else if (diffDays < 7) {
    return t('chat.daysAgo', { days: diffDays });
  } else {
    return date.toLocaleDateString(locale === 'vi' ? 'vi-VN' : 'en-US', {
      month: 'short',
      day: 'numeric',
      year: date.getFullYear() !== now.getFullYear() ? 'numeric' : undefined,
    });
  }
}

/**
 * EN: Copy icon SVG
 * VI: Icon SVG copy
 */
const CopyIcon = ({ className }: { className?: string }) => (
  <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={className}
  >
    <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>
);

/**
 * EN: Edit icon SVG
 * VI: Icon SVG edit
 */
const EditIcon = ({ className }: { className?: string }) => (
  <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={className}
  >
    <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>
);

/**
 * EN: Delete icon SVG
 * VI: Icon SVG delete
 */
const DeleteIcon = ({ className }: { className?: string }) => (
  <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={className}
  >
    <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>
);

/**
 * EN: Regenerate icon SVG
 * VI: Icon SVG regenerate
 */
const RegenerateIcon = ({ className }: { className?: string }) => (
  <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={className}
  >
    <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="M3 21v-5h5" />
  </svg>
);

/**
 * EN: Like icon SVG
 * VI: Icon SVG like
 */
const LikeIcon = ({ className }: { className?: string }) => (
  <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={className}
  >
    <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.67 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>
);

/**
 * EN: Dislike icon SVG
 * VI: Icon SVG dislike
 */
const DislikeIcon = ({ className }: { className?: string }) => (
  <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={className}
  >
    <path d="M17 14V2" />
    <path d="M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.67 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22h0a3.13 3.13 0 0 1-3-3.88Z" />
  </svg>
);

/**
 * EN: Share icon SVG
 * VI: Icon SVG share
 */
const ShareIcon = ({ className }: { className?: string }) => (
  <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={className}
  >
    <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>
);

/**
 * EN: Message bubble component - Displays chat messages with user/AI variants and actions
 * VI: Component Message bubble - Hiển thị tin nhắn chat với các biến thể user/AI và các hành động
 *
 * Features:
 * - User messages: Right aligned, blue bubble
 * - AI messages: Left aligned, grey bubble
 * - System messages: Centered, grey text
 * - Message actions on hover: Copy, Edit, Delete, Regenerate, Like/Dislike, Share
 * - Animation: Slide up + fade in
 *
 * Tính năng:
 * - Tin nhắn user: Căn phải, bubble xanh
 * - Tin nhắn AI: Căn trái, bubble xám
 * - Tin nhắn hệ thống: Căn giữa, text xám
 * - Hành động tin nhắn khi hover: Copy, Edit, Delete, Regenerate, Like/Dislike, Share
 * - Animation: Trượt lên + fade in
 *
 * @example
 * ```tsx
 * <MessageBubble
 *   sender="user"
 *   content="Hello, AI!"
 *   timestamp={new Date()}
 *   authorName="John Doe"
 *   showActions
 *   onCopy={() => navigator.clipboard.writeText("Hello, AI!")}
 * />
 * ```
 */
export function MessageBubble({
  sender,
  content,
  timestamp,
  authorName,
  authorAvatar,
  showActions = true,
  onCopy,
  onEdit,
  onDelete,
  onRegenerate,
  onLike,
  onDislike,
  onShare,
  isLiked = false,
  isDisliked = false,
  className,
}: MessageBubbleProps) {
  // EN: Translation hook / VI: Hook translation
  const t = useTranslations();
  const { locale } = useI18n();

  // EN: System messages - centered, simple text / VI: Tin nhắn hệ thống - căn giữa, text đơn giản
  if (sender === 'system') {
    return (
      <div
        className={cn(
          'flex justify-center items-center py-3 px-4',
          className
        )}
      >
        <span className="text-sm text-chat-timestamp">{content}</span>
      </div>
    );
  }

  const isUser = sender === 'user';
  const [isHovered, setIsHovered] = React.useState(false);

  return (
    <div
      className={cn(
        // EN: Base message container / VI: Container tin nhắn cơ bản
        'flex gap-3 px-4 py-3 group',
        // EN: User messages: Right aligned / VI: Tin nhắn user: Căn phải
        isUser && 'flex-row-reverse',
        // EN: AI messages: Left aligned / VI: Tin nhắn AI: Căn trái
        !isUser && 'flex-row',
        // EN: Animation: Fade in / VI: Animation: Fade in
        'opacity-0 animate-fadeIn',
        className
      )}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* EN: Avatar / VI: Avatar */}
      {!isUser && (
        <Avatar size="sm" className="flex-shrink-0">
          {authorAvatar && (
            <AvatarImage
              src={authorAvatar}
              alt={authorName ? t('chat.avatarOf', { name: authorName }) : t('chat.aiAssistantAvatar')}
            />
          )}
          <AvatarFallback aria-label={t('chat.aiAssistant')}>AI</AvatarFallback>
        </Avatar>
      )}

      {/* EN: Message content container / VI: Container nội dung tin nhắn */}
      <div
        className={cn(
          'flex flex-col',
          // EN: Mobile: Full width (95% for padding) / VI: Mobile: Full width (95% cho padding)
          'max-md:max-w-[95%]',
          // EN: Tablet: Medium width (60%) / VI: Tablet: Chiều rộng trung bình (60%)
          'md:max-w-[60%]',
          // EN: Desktop: Max width 80% / VI: Desktop: Chiều rộng tối đa 80%
          'lg:max-w-[80%]',
          // EN: User messages: Align to right / VI: Tin nhắn user: Căn về phải
          isUser && 'items-end',
          // EN: AI messages: Align to left / VI: Tin nhắn AI: Căn về trái
          !isUser && 'items-start'
        )}
      >
        {/* EN: Message header (author, timestamp) / VI: Header tin nhắn (tác giả, thời gian) */}
        {(authorName || timestamp) && (
          <div
            className={cn(
              'flex items-center gap-2 mb-1 px-1',
              isUser && 'flex-row-reverse'
            )}
          >
            {authorName && (
              <span className="text-xs font-medium text-text-secondary">
                {authorName}
              </span>
            )}
            {timestamp && (
              <span className="text-xs text-chat-timestamp">
                {formatTimestamp(timestamp, t, locale)}
              </span>
            )}
          </div>
        )}

        {/* EN: Message bubble / VI: Bubble tin nhắn */}
        <div
          className={cn(
            // EN: Base bubble styles / VI: Style bubble cơ bản
            'relative rounded-lg px-4 py-2.5 break-words',
            // EN: User bubble: Blue background / VI: Bubble user: Nền xanh
            isUser &&
              'bg-chat-user-bubble text-chat-user-text rounded-tr-none',
            // EN: AI bubble: Grey background / VI: Bubble AI: Nền xám
            !isUser &&
              'bg-chat-ai-bubble text-chat-ai-text rounded-tl-none'
          )}
        >
          {/* EN: Message text / VI: Text tin nhắn */}
          <p className="text-sm leading-relaxed whitespace-pre-wrap">{content}</p>

          {/* EN: Message actions (shown on hover) / VI: Hành động tin nhắn (hiện khi hover) */}
          {showActions && isHovered && (
            <div
              className={cn(
                // EN: Actions container / VI: Container hành động
                'absolute flex items-center gap-1 rounded-md bg-bg-elevated border border-border-primary p-1 shadow-lg',
                // EN: User messages: Position to top-right / VI: Tin nhắn user: Vị trí trên-phải
                isUser && 'top-0 right-full mr-2 flex-row-reverse',
                // EN: AI messages: Position to top-left / VI: Tin nhắn AI: Vị trí trên-trái
                !isUser && 'top-0 left-full ml-2'
              )}
            >
              {/* EN: Copy action / VI: Hành động copy */}
              {onCopy && (
                <button
                  onClick={onCopy}
                  className="p-1.5 rounded hover:bg-bg-tertiary active:scale-[0.95] active:bg-bg-elevated transition-all duration-[150ms] min-w-[44px] min-h-[44px] flex items-center justify-center"
                  aria-label={t('chat.copyMessage')}
                  title={t('chat.copy')}
                >
                  <CopyIcon className="w-4 h-4 text-text-secondary" />
                </button>
              )}

              {/* EN: Edit action (user messages only) / VI: Hành động edit (chỉ tin nhắn user) */}
              {isUser && onEdit && (
                <button
                  onClick={onEdit}
                  className="p-1.5 rounded hover:bg-bg-tertiary active:scale-[0.95] active:bg-bg-elevated transition-all duration-[150ms] min-w-[44px] min-h-[44px] flex items-center justify-center"
                  aria-label={t('chat.editMessage')}
                  title={t('chat.edit')}
                >
                  <EditIcon className="w-4 h-4 text-text-secondary" />
                </button>
              )}

              {/* EN: Delete action (user messages only) / VI: Hành động delete (chỉ tin nhắn user) */}
              {isUser && onDelete && (
                <button
                  onClick={onDelete}
                  className="p-1.5 rounded hover:bg-bg-tertiary active:scale-[0.95] active:bg-bg-elevated transition-all duration-[150ms] min-w-[44px] min-h-[44px] flex items-center justify-center"
                  aria-label={t('chat.deleteMessage')}
                  title={t('chat.delete')}
                >
                  <DeleteIcon className="w-4 h-4 text-accent-error" />
                </button>
              )}

              {/* EN: Regenerate action (AI messages only) / VI: Hành động regenerate (chỉ tin nhắn AI) */}
              {!isUser && onRegenerate && (
                <button
                  onClick={onRegenerate}
                  className="p-1.5 rounded hover:bg-bg-tertiary active:scale-[0.95] active:bg-bg-elevated transition-all duration-[150ms] min-w-[44px] min-h-[44px] flex items-center justify-center"
                  aria-label={t('chat.regenerateResponse')}
                  title={t('chat.regenerate')}
                >
                  <RegenerateIcon className="w-4 h-4 text-text-secondary" />
                </button>
              )}

              {/* EN: Like action / VI: Hành động like */}
              {onLike && (
                <button
                  onClick={onLike}
                  className={cn(
                    'p-1.5 rounded hover:bg-bg-tertiary active:scale-[0.95] active:bg-bg-elevated transition-all duration-[150ms] min-w-[44px] min-h-[44px] flex items-center justify-center',
                    isLiked && 'text-accent-success'
                  )}
                  aria-label={t('chat.likeMessage')}
                  title={t('chat.like')}
                >
                  <LikeIcon className="w-4 h-4" />
                </button>
              )}

              {/* EN: Dislike action / VI: Hành động dislike */}
              {onDislike && (
                <button
                  onClick={onDislike}
                  className={cn(
                    'p-1.5 rounded hover:bg-bg-tertiary active:scale-[0.95] active:bg-bg-elevated transition-all duration-[150ms] min-w-[44px] min-h-[44px] flex items-center justify-center',
                    isDisliked && 'text-accent-error'
                  )}
                  aria-label={t('chat.dislikeMessage')}
                  title={t('chat.dislike')}
                >
                  <DislikeIcon className="w-4 h-4" />
                </button>
              )}

              {/* EN: Share action / VI: Hành động share */}
              {onShare && (
                <button
                  onClick={onShare}
                  className="p-1.5 rounded hover:bg-bg-tertiary active:scale-[0.95] active:bg-bg-elevated transition-all duration-[150ms] min-w-[44px] min-h-[44px] flex items-center justify-center"
                  aria-label={t('chat.shareMessage')}
                  title={t('chat.share')}
                >
                  <ShareIcon className="w-4 h-4 text-text-secondary" />
                </button>
              )}
            </div>
          )}
        </div>
      </div>

      {/* EN: User avatar (right side) / VI: Avatar user (bên phải) */}
      {isUser && (
        <Avatar size="sm" className="flex-shrink-0">
          {authorAvatar && (
            <AvatarImage
              src={authorAvatar}
              alt={authorName ? t('chat.avatarOf', { name: authorName }) : t('chat.userAvatar')}
            />
          )}
          <AvatarFallback aria-label={authorName ? t('chat.avatarOf', { name: authorName }) : t('chat.userAvatar')}>
            {authorName
              ? authorName
                  .split(' ')
                  .map((n) => n[0])
                  .join('')
                  .toUpperCase()
              : 'U'}
          </AvatarFallback>
        </Avatar>
      )}
    </div>
  );
}
