'use client';

import * as React from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Edit, Trash2, Ban, CheckCircle2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useTranslation } from '@/hooks/use-translation';

/**
 * EN: User interface
 * VI: Interface cho User
 */
export interface User {
  id: string;
  email: string;
  firstName?: string;
  lastName?: string;
  role: string;
  status: 'active' | 'inactive' | 'banned';
  avatarUrl?: string;
  createdAt: string;
  lastLoginAt?: string;
}

/**
 * EN: Activity log entry
 * VI: Entry log hoạt động
 */
export interface ActivityLog {
  id: string;
  action: string;
  description: string;
  timestamp: string;
}

/**
 * EN: Message history entry
 * VI: Entry lịch sử tin nhắn
 */
export interface MessageHistory {
  id: string;
  content: string;
  conversationId: string;
  timestamp: string;
}

/**
 * EN: UserDetailsModal component props
 * VI: Props của component UserDetailsModal
 */
export interface UserDetailsModalProps {
  /**
   * EN: User data / VI: Dữ liệu người dùng
   */
  user: User | null;
  /**
   * EN: Modal open state / VI: Trạng thái mở modal
   */
  open: boolean;
  /**
   * EN: Callback when modal closes / VI: Callback khi modal đóng
   */
  onOpenChange: (open: boolean) => void;
  /**
   * EN: Activity logs / VI: Log hoạt động
   */
  activityLogs?: ActivityLog[];
  /**
   * EN: Message history / VI: Lịch sử tin nhắn
   */
  messageHistory?: MessageHistory[];
  /**
   * EN: Callback when edit is clicked / VI: Callback khi edit được click
   */
  onEdit?: (user: User) => void;
  /**
   * EN: Callback when delete is clicked / VI: Callback khi delete được click
   */
  onDelete?: (userId: string) => void;
  /**
   * EN: Callback when deactivate is clicked / VI: Callback khi deactivate được click
   */
  onDeactivate?: (userId: string) => void;
}

/**
 * EN: UserDetailsModal component - Modal showing user details, activity timeline, and message history
 * VI: Component UserDetailsModal - Modal hiển thị chi tiết người dùng, timeline hoạt động và lịch sử tin nhắn
 *
 * Features:
 * - User profile information
 * - Activity timeline
 * - Message history
 * - Edit, Delete, Deactivate actions
 *
 * Tính năng:
 * - Thông tin profile người dùng
 * - Timeline hoạt động
 * - Lịch sử tin nhắn
 * - Các hành động Edit, Delete, Deactivate
 */
export function UserDetailsModal({
  user,
  open,
  onOpenChange,
  activityLogs = [],
  messageHistory = [],
  onEdit,
  onDelete,
  onDeactivate,
}: UserDetailsModalProps) {
  const { t, locale } = useTranslation();
  
  if (!user) return null;

  // EN: Get user initials / VI: Lấy initials của user
  const getUserInitials = () => {
    if (user.firstName && user.lastName) {
      return `${user.firstName.charAt(0)}${user.lastName.charAt(0)}`.toUpperCase();
    }
    return user.email.charAt(0).toUpperCase();
  };

  // EN: Format timestamp / VI: Format timestamp
  const formatTimestamp = (date: string) => {
    return new Date(date).toLocaleString(locale === 'vi' ? 'vi-VN' : 'en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // EN: Get status badge color / VI: Lấy màu badge trạng thái
  const getStatusColor = () => {
    switch (user.status) {
      case 'active':
        return 'bg-accent-success/20 text-accent-success border-accent-success/30';
      case 'inactive':
        return 'bg-text-tertiary/20 text-text-tertiary border-text-tertiary/30';
      case 'banned':
        return 'bg-accent-error/20 text-accent-error border-accent-error/30';
      default:
        return 'bg-text-tertiary/20 text-text-tertiary border-text-tertiary/30';
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{t('admin.users.viewDetails')}</DialogTitle>
          <DialogDescription>
            {t('admin.users.description')}
          </DialogDescription>
        </DialogHeader>

        <Tabs defaultValue="profile" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="profile">Profile</TabsTrigger>
            <TabsTrigger value="activity">{t('admin.activity.recentActivity')}</TabsTrigger>
            <TabsTrigger value="messages">{t('admin.messages.title')}</TabsTrigger>
          </TabsList>

          {/* EN: Profile tab / VI: Tab Profile */}
          <TabsContent value="profile" className="space-y-4">
            <Card>
              <CardHeader>
                <div className="flex items-center gap-4">
                  <Avatar size="lg" className="h-20 w-20">
                    {user.avatarUrl && (
                      <AvatarImage src={user.avatarUrl} alt={user.email} />
                    )}
                    <AvatarFallback>{getUserInitials()}</AvatarFallback>
                  </Avatar>
                  <div className="flex-1">
                    <h3 className="text-xl font-semibold text-text-primary">
                      {user.firstName && user.lastName
                        ? `${user.firstName} ${user.lastName}`
                        : user.email}
                    </h3>
                    <p className="text-sm text-text-tertiary mt-1">{user.email}</p>
                    <div className="mt-2">
                      <span
                        className={cn(
                          'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border',
                          getStatusColor()
                        )}
                      >
                        {user.status === 'active' && (
                          <CheckCircle2 className="h-3 w-3 mr-1" />
                        )}
                        {user.status === 'banned' && (
                          <Ban className="h-3 w-3 mr-1" />
                        )}
                        {user.status === 'active' 
                          ? t('admin.users.active')
                          : user.status === 'inactive'
                          ? t('admin.users.inactive')
                          : t('admin.users.banned')}
                      </span>
                    </div>
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-xs text-text-tertiary mb-1">{t('admin.users.role')}</p>
                    <p className="text-sm font-medium text-text-primary">{user.role}</p>
                  </div>
                  <div>
                    <p className="text-xs text-text-tertiary mb-1">
                      {t('admin.users.createdAt')}
                    </p>
                    <p className="text-sm font-medium text-text-primary">
                      {formatTimestamp(user.createdAt)}
                    </p>
                  </div>
                  {user.lastLoginAt && (
                    <div>
                      <p className="text-xs text-text-tertiary mb-1">
                        {t('admin.users.lastLogin')}
                      </p>
                      <p className="text-sm font-medium text-text-primary">
                        {formatTimestamp(user.lastLoginAt)}
                      </p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* EN: Action buttons / VI: Nút hành động */}
            <div className="flex items-center justify-end gap-2">
              {onEdit && (
                <Button variant="secondary" size="sm" onClick={() => onEdit(user)}>
                  <Edit className="h-4 w-4 mr-2" />
                  {t('admin.users.editUser')}
                </Button>
              )}
              {onDeactivate && (
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() => onDeactivate(user.id)}
                >
                  <Ban className="h-4 w-4 mr-2" />
                  {user.status === 'active' ? t('admin.users.deactivate') : t('admin.users.activate')}
                </Button>
              )}
              {onDelete && (
                <Button
                  variant="danger"
                  size="sm"
                  onClick={() => {
                    if (confirm(t('admin.users.deleteUser'))) {
                      onDelete(user.id);
                    }
                  }}
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  {t('common.delete')}
                </Button>
              )}
            </div>
          </TabsContent>

          {/* EN: Activity tab / VI: Tab Activity */}
          <TabsContent value="activity" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle>{t('admin.activity.recentActivity')}</CardTitle>
              </CardHeader>
              <CardContent>
                {activityLogs.length === 0 ? (
                  <p className="text-sm text-text-tertiary text-center py-8">
                    {t('admin.activity.noActivity')}
                  </p>
                ) : (
                  <div className="space-y-4">
                    {activityLogs.map((log) => (
                      <div
                        key={log.id}
                        className="flex items-start gap-4 pb-4 border-b border-border-primary last:border-0"
                      >
                        <div className="flex-1">
                          <p className="text-sm font-medium text-text-primary">
                            {log.action}
                          </p>
                          <p className="text-sm text-text-secondary mt-1">
                            {log.description}
                          </p>
                          <p className="text-xs text-text-tertiary mt-1">
                            {formatTimestamp(log.timestamp)}
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          {/* EN: Messages tab / VI: Tab Messages */}
          <TabsContent value="messages" className="space-y-4">
            <Card>
              <CardHeader>
                <CardTitle>{t('admin.messages.title')}</CardTitle>
              </CardHeader>
              <CardContent>
                {messageHistory.length === 0 ? (
                  <p className="text-sm text-text-tertiary text-center py-8">
                    {t('common.noData')}
                  </p>
                ) : (
                  <div className="space-y-4">
                    {messageHistory.map((message) => (
                      <div
                        key={message.id}
                        className="p-4 rounded-lg bg-bg-tertiary border border-border-primary"
                      >
                        <p className="text-sm text-text-primary">{message.content}</p>
                        <p className="text-xs text-text-tertiary mt-2">
                          {formatTimestamp(message.timestamp)}
                        </p>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
