'use client';

import * as React from 'react';
import { cn } from '@/shared/lib/utils';
import { Button } from '@/features/shared/components/ui/button';
import { Input } from '@/features/shared/components/ui/input';
import { Avatar, AvatarFallback } from '@/features/shared/components/ui/avatar';
import { useAuthStore } from '@/stores/auth-store';
import { useTranslations } from 'next-intl';
import { useI18n } from '@/features/theme';

/**
 * EN: Conversation interface
 * VI: Interface cho Conversation
 */
export interface Conversation {
  /** EN: Unique conversation ID / VI: ID duy nhất của conversation */
  id: string;
  /** EN: Conversation title / VI: Tiêu đề conversation */
  title: string;
  /** EN: Last message preview / VI: Xem trước tin nhắn cuối */
  lastMessage?: string;
  /** EN: Last message timestamp / VI: Timestamp tin nhắn cuối */
  lastMessageAt?: Date;
  /** EN: Whether conversation is selected / VI: Conversation có được chọn không */
  isSelected?: boolean;
}

/**
 * EN: ConversationSidebar component props
 * VI: Props của component ConversationSidebar
 */
export interface ConversationSidebarProps {
  /** EN: List of conversations / VI: Danh sách conversations */
  conversations?: Conversation[];
  /** EN: Selected conversation ID / VI: ID conversation được chọn */
  selectedConversationId?: string;
  /** EN: Callback when conversation is selected / VI: Callback khi conversation được chọn */
  onSelectConversation?: (conversationId: string) => void;
  /** EN: Callback when new chat button is clicked / VI: Callback khi nút new chat được click */
  onNewChat?: () => void;
  /** EN: Additional CSS classes / VI: Các class CSS bổ sung */
  className?: string;
}

/**
 * EN: ConversationSidebar component - Sidebar with conversation list, search, and user profile
 * VI: Component ConversationSidebar - Sidebar với danh sách conversation, tìm kiếm, và profile người dùng
 *
 * Features:
 * - New Chat button
 * - Search conversations input
 * - Scrollable conversation list
 * - User profile section (sticky bottom)
 *
 * Tính năng:
 * - Nút New Chat
 * - Input tìm kiếm conversations
 * - Danh sách conversation có thể scroll
 * - Phần profile người dùng (sticky bottom)
 */
export function ConversationSidebar({
  conversations = [],
  selectedConversationId,
  onSelectConversation,
  onNewChat,
  className,
}: ConversationSidebarProps) {
  // EN: Translation hook / VI: Hook translation
  const t = useTranslations();
  const { locale } = useI18n();
  // EN: Get current user from auth store / VI: Lấy user hiện tại từ auth store
  const { user } = useAuthStore();

  // EN: Search state / VI: State tìm kiếm
  const [searchQuery, setSearchQuery] = React.useState('');

  // EN: Filter conversations based on search query / VI: Lọc conversations dựa trên search query
  const filteredConversations = React.useMemo(() => {
    if (!searchQuery.trim()) {
      return conversations;
    }
    const query = searchQuery.toLowerCase();
    return conversations.filter(
      (conv) =>
        conv.title.toLowerCase().includes(query) ||
        conv.lastMessage?.toLowerCase().includes(query)
    );
  }, [conversations, searchQuery]);

  // EN: Format timestamp to relative time / VI: Format timestamp thành thời gian tương đối
  const formatRelativeTime = (date?: Date): string => {
    if (!date) return '';
    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');
    if (diffMins < 60) return `${diffMins}m`;
    if (diffHours < 24) return `${diffHours}h`;
    if (diffDays < 7) return `${diffDays}d`;
    return date.toLocaleDateString(locale === 'vi' ? 'vi-VN' : 'en-US', { month: 'short', day: 'numeric' });
  };

  // EN: Get user initials for avatar fallback / VI: Lấy initials của user cho avatar fallback
  const getUserInitials = (email?: string): string => {
    if (!email) return 'U';
    const parts = email.split('@')[0].split(/[._-]/);
    if (parts.length >= 2) {
      return (parts[0][0] + parts[1][0]).toUpperCase();
    }
    return email.substring(0, 2).toUpperCase();
  };

  return (
    <div
      className={cn(
        // EN: Base styles - fixed width sidebar / VI: Styles cơ bản - sidebar cố định chiều rộng
        'flex flex-col h-full w-sidebar bg-bg-secondary border-r border-border-primary',
        className
      )}
    >
      {/* EN: Header section with New Chat button / VI: Phần header với nút New Chat */}
      <header className="p-4 border-b border-border-primary" role="banner">
        <Button
          variant="primary"
          size="md"
          className="w-full"
          onClick={onNewChat}
          aria-label={t('chat.newChat')}
        >
          {/* EN: Plus icon / VI: Icon dấu cộng */}
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
            className="mr-2 h-4 w-4"
          >
            <path d="M5 12h14" />
            <path d="M12 5v14" />
          </svg>
          {t('chat.newChat')}
        </Button>
      </header>

      {/* EN: Search section / VI: Phần tìm kiếm */}
      <nav className="p-4 border-b border-border-primary" role="search" aria-label={t('chat.searchConversations')}>
        <Input
          type="search"
          placeholder={t('chat.searchPlaceholder')}
          value={searchQuery}
          onChange={setSearchQuery}
          className="w-full"
          aria-label={t('chat.searchConversations')}
        />
      </nav>

      {/* EN: Conversations list (scrollable) / VI: Danh sách conversations (có thể scroll) */}
      <nav className="flex-1 overflow-y-auto" role="navigation" aria-label={t('chat.conversationList')}>
        {filteredConversations.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full p-8 text-center">
            <p className="text-text-tertiary text-sm">
              {searchQuery
                ? t('chat.noConversationsFound')
                : t('chat.noConversations')}
            </p>
          </div>
        ) : (
          <div className="p-2">
            {filteredConversations.map((conversation) => (
              <button
                key={conversation.id}
                onClick={() => onSelectConversation?.(conversation.id)}
                className={cn(
                  // EN: Base conversation item styles / VI: Styles cơ bản cho item conversation
                  'w-full text-left p-3 rounded-lg mb-2 transition-all duration-[150ms]',
                  // EN: Touch-friendly: Minimum 44px height, 8px spacing / VI: Thân thiện với chạm: Chiều cao tối thiểu 44px, khoảng cách 8px
                  'min-h-[44px]',
                  'hover:bg-bg-tertiary active:scale-[0.98] active:bg-bg-elevated',
                  'focus:outline-none focus:ring-2 focus:ring-accent-primary focus:ring-offset-2 focus:ring-offset-bg-secondary',
                  // EN: Selected state / VI: Trạng thái được chọn
                  conversation.id === selectedConversationId || conversation.isSelected
                    ? 'bg-bg-tertiary border-l-3 border-accent-primary'
                    : 'bg-transparent'
                )}
                aria-label={`${t('chat.conversation')}: ${conversation.title}`}
              >
                {/* EN: Conversation title / VI: Tiêu đề conversation */}
                <div className="flex items-start justify-between gap-2 mb-1">
                  <h3 className="text-sm font-medium text-text-primary truncate flex-1">
                    {conversation.title}
                  </h3>
                  {conversation.lastMessageAt && (
                    <span className="text-xs text-chat-timestamp whitespace-nowrap">
                      {formatRelativeTime(conversation.lastMessageAt)}
                    </span>
                  )}
                </div>

                {/* EN: Last message preview / VI: Xem trước tin nhắn cuối */}
                {conversation.lastMessage && (
                  <p className="text-xs text-text-tertiary truncate">
                    {conversation.lastMessage}
                  </p>
                )}
              </button>
            ))}
          </div>
        )}
      </nav>

      {/* EN: User profile section (sticky bottom) / VI: Phần profile người dùng (sticky bottom) */}
      {user && (
        <div className="p-4 border-t border-border-primary bg-bg-secondary">
          <div className="flex items-center gap-3">
            <Avatar size="sm">
              <AvatarFallback>{getUserInitials(user.email)}</AvatarFallback>
            </Avatar>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-text-primary truncate">
                {user.email}
              </p>
              <p className="text-xs text-text-tertiary truncate">
                {user.role}
              </p>
            </div>
            {/* EN: Settings icon / VI: Icon cài đặt */}
            <button
              className="p-2 rounded-md hover:bg-bg-tertiary transition-colors"
              aria-label={t('settings.title')}
            >
              <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 text-text-tertiary"
              >
                <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z" />
                <circle cx="12" cy="12" r="3" />
              </svg>
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
