'use client';

import * as React from 'react';
import { cn } from '@/lib/utils';
import { useTranslation } from '@/hooks/use-translation';

/**
 * EN: Activity status type
 * VI: Loại trạng thái hoạt động
 */
export type ActivityStatus = 'success' | 'warning' | 'error' | 'info' | 'pending';

/**
 * EN: Activity action type
 * VI: Loại hành động hoạt động
 */
export type ActivityAction =
  | 'user_created'
  | 'user_updated'
  | 'user_deleted'
  | 'user_login'
  | 'user_logout'
  | 'message_sent'
  | 'message_deleted'
  | 'settings_updated'
  | 'system_backup'
  | 'system_restore';

/**
 * EN: Recent activity item interface
 * VI: Interface cho item hoạt động gần đây
 */
export interface RecentActivity {
  /**
   * EN: Unique activity identifier / VI: Mã định danh duy nhất cho hoạt động
   */
  id: string;
  /**
   * EN: User who performed the action / VI: Người dùng thực hiện hành động
   */
  user: {
    /**
     * EN: User ID / VI: ID người dùng
     */
    id: string;
    /**
     * EN: User name / VI: Tên người dùng
     */
    name: string;
    /**
     * EN: User email / VI: Email người dùng
     */
    email: string;
    /**
     * EN: User avatar URL (optional) / VI: URL avatar người dùng (tùy chọn)
     */
    avatarUrl?: string;
  };
  /**
   * EN: Action performed / VI: Hành động được thực hiện
   */
  action: ActivityAction;
  /**
   * EN: Action description / VI: Mô tả hành động
   */
  description: string;
  /**
   * EN: Activity status / VI: Trạng thái hoạt động
   */
  status: ActivityStatus;
  /**
   * EN: Timestamp when activity occurred / VI: Timestamp khi hoạt động xảy ra
   */
  timestamp: Date | string;
  /**
   * EN: Additional metadata (optional) / VI: Metadata bổ sung (tùy chọn)
   */
  metadata?: Record<string, unknown>;
}

/**
 * EN: RecentActivityTable component props
 * VI: Props của component RecentActivityTable
 */
export interface RecentActivityTableProps {
  /**
   * EN: Array of recent activities / VI: Mảng các hoạt động gần đây
   */
  activities: RecentActivity[];
  /**
   * EN: Current page number (1-indexed) / VI: Số trang hiện tại (bắt đầu từ 1)
   */
  currentPage?: number;
  /**
   * EN: Number of items per page / VI: Số item mỗi trang
   */
  itemsPerPage?: number;
  /**
   * EN: Total number of items (for server-side pagination) / VI: Tổng số item (cho pagination phía server)
   */
  totalItems?: number;
  /**
   * EN: Callback when page changes / VI: Callback khi trang thay đổi
   */
  onPageChange?: (page: number) => void;
  /**
   * EN: Callback for quick action click / VI: Callback khi click quick action
   */
  onQuickAction?: (activityId: string, action: string) => void;
  /**
   * EN: Loading state / VI: Trạng thái loading
   */
  loading?: boolean;
  /**
   * EN: Additional CSS classes / VI: Các class CSS bổ sung
   */
  className?: string;
}

/**
 * EN: Get user initials for avatar fallback
 * VI: Lấy initials của user cho avatar fallback
 */
function getUserInitials(name: string): string {
  return name
    .split(' ')
    .map((n) => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);
}

/**
 * EN: Format timestamp to relative time
 * VI: Format timestamp thành thời gian tương đối
 */
function formatRelativeTime(date: Date | string, locale: string = 'en'): string {
  const now = new Date();
  const activityDate = typeof date === 'string' ? new Date(date) : date;
  const diffMs = now.getTime() - activityDate.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);

  // EN: Use locale-aware formatting / VI: Sử dụng formatting theo locale
  if (diffMins < 1) return locale === 'vi' ? 'Vừa xong' : 'Just now';
  if (diffMins < 60) {
    return locale === 'vi' ? `${diffMins} phút trước` : `${diffMins}m ago`;
  }
  if (diffHours < 24) {
    return locale === 'vi' ? `${diffHours} giờ trước` : `${diffHours}h ago`;
  }
  if (diffDays < 7) {
    return locale === 'vi' ? `${diffDays} ngày trước` : `${diffDays}d ago`;
  }
  return activityDate.toLocaleDateString(locale === 'vi' ? 'vi-VN' : 'en-US', {
    month: 'short',
    day: 'numeric',
    year: diffDays >= 365 ? 'numeric' : undefined,
  });
}

/**
 * EN: Get status badge styles
 * VI: Lấy styles cho status badge
 */
function getStatusBadgeStyles(status: ActivityStatus): string {
  const styles = {
    success:
      'bg-accent-success/20 text-accent-success border-accent-success/30',
    warning:
      'bg-accent-warning/20 text-accent-warning border-accent-warning/30',
    error:
      'bg-accent-error/20 text-accent-error border-accent-error/30',
    info: 'bg-accent-info/20 text-accent-info border-accent-info/30',
    pending:
      'bg-text-tertiary/20 text-text-tertiary border-text-tertiary/30',
  };
  return styles[status];
}

/**
 * EN: Get status label
 * VI: Lấy label cho status
 */
function getStatusLabel(status: ActivityStatus, t: (key: string) => string): string {
  const labels: Record<ActivityStatus, string> = {
    success: t('admin.activity.status.success'),
    warning: t('admin.activity.status.warning'),
    error: t('admin.activity.status.error'),
    info: t('admin.activity.status.info'),
    pending: t('admin.activity.status.pending'),
  };
  return labels[status];
}

/**
 * EN: Get action label
 * VI: Lấy label cho action
 */
function getActionLabel(action: ActivityAction, t: (key: string) => string): string {
  const labels: Record<ActivityAction, string> = {
    user_created: t('admin.activity.actions.userCreated'),
    user_updated: t('admin.activity.actions.userUpdated'),
    user_deleted: t('admin.activity.actions.userDeleted'),
    user_login: t('admin.activity.actions.userLogin'),
    user_logout: t('admin.activity.actions.userLogout'),
    message_sent: t('admin.activity.actions.messageSent'),
    message_deleted: t('admin.activity.actions.messageDeleted'),
    settings_updated: t('admin.activity.actions.settingsUpdated'),
    system_backup: t('admin.activity.actions.systemBackup'),
    system_restore: t('admin.activity.actions.systemRestore'),
  };
  return labels[action] || action;
}

/**
 * EN: RecentActivityTable component - Displays recent activities with pagination
 * VI: Component RecentActivityTable - Hiển thị các hoạt động gần đây với pagination
 *
 * Features:
 * - User avatar + name
 * - Action performed
 * - Timestamp (relative)
 * - Status badge
 * - Quick actions
 * - Pagination
 *
 * Tính năng:
 * - Avatar + tên người dùng
 * - Hành động được thực hiện
 * - Timestamp (tương đối)
 * - Badge trạng thái
 * - Quick actions
 * - Pagination
 *
 * @example
 * ```tsx
 * <RecentActivityTable
 *   activities={activities}
 *   currentPage={1}
 *   itemsPerPage={10}
 *   onPageChange={(page) => setPage(page)}
 *   onQuickAction={(id, action) => handleAction(id, action)}
 * />
 * ```
 */
export function RecentActivityTable({
  activities,
  currentPage = 1,
  itemsPerPage = 10,
  totalItems,
  onPageChange,
  onQuickAction,
  loading = false,
  className,
}: RecentActivityTableProps) {
  const { t, locale } = useTranslation();
  
  // EN: Calculate pagination / VI: Tính toán pagination
  const totalPages = totalItems
    ? Math.ceil(totalItems / itemsPerPage)
    : Math.ceil(activities.length / itemsPerPage);

  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedActivities = totalItems
    ? activities // EN: Server-side pagination / VI: Pagination phía server
    : activities.slice(startIndex, endIndex); // EN: Client-side pagination / VI: Pagination phía client

  // EN: Handle page change / VI: Xử lý thay đổi trang
  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages && onPageChange) {
      onPageChange(page);
    }
  };

  // EN: Handle quick action / VI: Xử lý quick action
  const handleQuickAction = (activityId: string, action: string) => {
    if (onQuickAction) {
      onQuickAction(activityId, action);
    }
  };

  return (
    <div
      className={cn(
        'bg-bg-secondary rounded-xl border border-border-primary overflow-hidden',
        className
      )}
    >
      {/* EN: Table Header / VI: Header bảng */}
      <div className="px-6 py-4 border-b border-border-primary">
        <h3 className="text-lg font-semibold text-text-primary">
          {t('admin.activity.recentActivity')}
        </h3>
        <p className="text-sm text-text-tertiary mt-1">
          {t('admin.activity.latestSystemActivities')}
        </p>
      </div>

      {/* EN: Table Content / VI: Nội dung bảng */}
      {/* EN: Mobile: Horizontal scroll / VI: Mobile: Scroll ngang */}
      <div className="overflow-x-auto -mx-4 sm:mx-0">
        <div className="inline-block min-w-full align-middle sm:min-w-0 px-4 sm:px-0">
        {loading ? (
          // EN: Loading state / VI: Trạng thái loading
          <div className="p-8 text-center">
            <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-accent-primary border-r-transparent" />
            <p className="mt-4 text-sm text-text-tertiary">
              {t('common.loading')}
            </p>
          </div>
        ) : paginatedActivities.length === 0 ? (
          // EN: Empty state / VI: Trạng thái trống
          <div className="p-8 text-center">
            <p className="text-sm text-text-tertiary">
              {t('admin.activity.noActivity')}
            </p>
          </div>
        ) : (
          <table className="w-full">
            <thead>
              <tr className="border-b border-border-primary">
                <th className="px-6 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
                  {t('common.user')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
                  {t('common.actions')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
                  {t('admin.users.status')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
                  {t('admin.users.lastLogin')}
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-text-tertiary uppercase tracking-wider">
                  {t('common.actions')}
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border-primary">
              {paginatedActivities.map((activity) => (
                <tr
                  key={activity.id}
                  className="hover:bg-bg-tertiary transition-colors duration-[150ms]"
                >
                  {/* EN: User column / VI: Cột người dùng */}
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center">
                      {/* EN: Avatar / VI: Avatar */}
                      <div className="relative flex-shrink-0 h-10 w-10">
                        {activity.user.avatarUrl ? (
                          <img
                            src={activity.user.avatarUrl}
                            alt={`${t('common.user')}: ${activity.user.name}`}
                            className="h-10 w-10 rounded-full object-cover"
                            loading="lazy"
                          />
                        ) : (
                          <div className="h-10 w-10 rounded-full bg-chat-ai-bubble flex items-center justify-center">
                            <span className="text-sm font-medium text-text-primary">
                              {getUserInitials(activity.user.name)}
                            </span>
                          </div>
                        )}
                      </div>
                      <div className="ml-3">
                        <div className="text-sm font-medium text-text-primary">
                          {activity.user.name}
                        </div>
                        <div className="text-sm text-text-tertiary">
                          {activity.user.email}
                        </div>
                      </div>
                    </div>
                  </td>

                  {/* EN: Action column / VI: Cột hành động */}
                  <td className="px-6 py-4">
                    <div className="text-sm text-text-secondary">
                      {getActionLabel(activity.action, t)}
                    </div>
                    <div className="text-xs text-text-tertiary mt-1">
                      {activity.description}
                    </div>
                  </td>

                  {/* EN: Status column / VI: Cột trạng thái */}
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span
                      className={cn(
                        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border',
                        getStatusBadgeStyles(activity.status)
                      )}
                    >
                      {getStatusLabel(activity.status, t)}
                    </span>
                  </td>

                  {/* EN: Time column / VI: Cột thời gian */}
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-text-tertiary">
                    {formatRelativeTime(activity.timestamp, locale)}
                  </td>

                  {/* EN: Quick actions column / VI: Cột quick actions */}
                  <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleQuickAction(activity.id, 'view')}
                        className="text-accent-primary hover:brightness-110 transition-colors duration-[150ms] min-h-[44px] px-2 py-1"
                        aria-label={t('admin.users.viewDetails')}
                      >
                        {t('admin.users.viewDetails')}
                      </button>
                      <span className="text-border-primary">|</span>
                      <button
                        onClick={() => handleQuickAction(activity.id, 'copy')}
                        className="text-accent-primary hover:brightness-110 transition-colors duration-[150ms] min-h-[44px] px-2 py-1"
                        aria-label={t('common.copy')}
                      >
                        {t('common.copy')}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        </div>
      </div>

      {/* EN: Pagination / VI: Pagination */}
      {totalPages > 1 && (
        <div className="px-6 py-4 border-t border-border-primary flex items-center justify-between">
          <div className="text-sm text-text-tertiary">
            {totalItems ? (
              <>
                {t('common.showing')}{' '}
                <span className="font-medium text-text-secondary">
                  {startIndex + 1}
                </span>{' '}
                {t('common.to')}{' '}
                <span className="font-medium text-text-secondary">
                  {Math.min(endIndex, totalItems)}
                </span>{' '}
                {t('common.of')}{' '}
                <span className="font-medium text-text-secondary">{totalItems}</span>{' '}
                {t('common.results')}
              </>
            ) : (
              <>
                {t('common.showing')}{' '}
                <span className="font-medium text-text-secondary">
                  {startIndex + 1}
                </span>{' '}
                {t('common.to')}{' '}
                <span className="font-medium text-text-secondary">
                  {Math.min(endIndex, activities.length)}
                </span>{' '}
                {t('common.of')}{' '}
                <span className="font-medium text-text-secondary">
                  {activities.length}
                </span>{' '}
                {t('common.results')}
              </>
            )}
          </div>

          <div className="flex items-center gap-2">
            {/* EN: Previous button / VI: Nút trước */}
            <button
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1 || loading}
              className={cn(
                'px-3 py-1.5 text-sm font-medium rounded-md transition-all duration-[150ms]',
                'border border-border-primary',
                // EN: Mobile: Minimum 44px touch target / VI: Mobile: Touch target tối thiểu 44px
                'min-w-[44px] min-h-[44px]',
                currentPage === 1 || loading
                  ? 'opacity-50 cursor-not-allowed text-text-tertiary'
                  : 'text-text-secondary hover:bg-bg-tertiary hover:border-border-secondary hover:scale-[1.02] active:scale-[0.98]'
              )}
              aria-label={t('common.previous')}
            >
              <span className="hidden sm:inline">{t('common.previous')}</span>
              <span className="sm:hidden">{t('common.previous')}</span>
            </button>

            {/* EN: Page numbers / VI: Số trang */}
            <div className="flex items-center gap-1">
              {Array.from({ length: totalPages }, (_, i) => i + 1).map(
                (page) => {
                  // EN: Show first page, last page, current page, and pages around current / VI: Hiển thị trang đầu, cuối, hiện tại và các trang xung quanh
                  if (
                    page === 1 ||
                    page === totalPages ||
                    (page >= currentPage - 1 && page <= currentPage + 1)
                  ) {
                    return (
                      <button
                        key={page}
                        onClick={() => handlePageChange(page)}
                        disabled={loading}
                        className={cn(
                          'px-3 py-1.5 text-sm font-medium rounded-md transition-all duration-[150ms]',
                          'border border-border-primary',
                          page === currentPage
                            ? 'bg-accent-primary text-white border-accent-primary'
                            : 'text-text-secondary hover:bg-bg-tertiary hover:border-border-secondary hover:scale-[1.02] active:scale-[0.98]',
                          loading && 'opacity-50 cursor-not-allowed'
                        )}
                        aria-label={`${t('common.page')} ${page}`}
                        aria-current={page === currentPage ? 'page' : undefined}
                      >
                        {page}
                      </button>
                    );
                  } else if (
                    page === currentPage - 2 ||
                    page === currentPage + 2
                  ) {
                    return (
                      <span
                        key={page}
                        className="px-2 text-sm text-text-tertiary"
                      >
                        ...
                      </span>
                    );
                  }
                  return null;
                }
              )}
            </div>

            {/* EN: Next button / VI: Nút sau */}
            <button
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages || loading}
              className={cn(
                'px-3 py-1.5 text-sm font-medium rounded-md transition-all duration-[150ms]',
                'border border-border-primary',
                // EN: Mobile: Minimum 44px touch target / VI: Mobile: Touch target tối thiểu 44px
                'min-w-[44px] min-h-[44px]',
                currentPage === totalPages || loading
                  ? 'opacity-50 cursor-not-allowed text-text-tertiary'
                  : 'text-text-secondary hover:bg-bg-tertiary hover:border-border-secondary hover:scale-[1.02] active:scale-[0.98]'
              )}
              aria-label={t('common.next')}
            >
              <span className="hidden sm:inline">{t('common.next')}</span>
              <span className="sm:hidden">{t('common.next')}</span>
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
