'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';

const UserDetailPage: React.FC = () => {
  const params = useParams();
  const userId = params.id as string;
  const [activeTab, setActiveTab] = useState('overview');

  // Mock user data
  const user = {
    id: userId,
    name: 'Andi Wijaya',
    email: 'andi.wijaya@trainee.dapurmbg.com',
    role: 'student',
    status: 'active',
    class: 'Batch-A-2024',
    studentId: 'MBG2024001',
    phone: '081234567890',
    address: 'Jl. Merdeka No. 123, Jakarta',
    dateOfBirth: '2000-05-15',
    gender: 'male',
    createdAt: '2024-01-05T08:00:00',
    lastLogin: '2024-01-15T09:05:00',
    totalExams: 12,
    completedExams: 10,
    averageScore: 85.5,
    avatar: null
  };

  // Mock exam history
  const examHistory = [
    {
      id: '1',
      title: 'Ujian Sertifikasi - Teknik Dasar Memasak',
      date: '2024-01-10T10:00:00',
      score: 88,
      maxScore: 100,
      status: 'completed',
      duration: '01:45:30'
    },
    {
      id: '2',
      title: 'Quiz Mingguan - Hygiene dan Sanitasi Dapur',
      date: '2024-01-08T14:00:00',
      score: 92,
      maxScore: 100,
      status: 'completed',
      duration: '00:25:15'
    },
    {
      id: '3',
      title: 'Evaluasi Praktik - Masakan Indonesia',
      date: '2024-01-05T09:00:00',
      score: 78,
      maxScore: 100,
      status: 'completed',
      duration: '02:15:45'
    },
    {
      id: '4',
      title: 'Quiz - Manajemen Bahan Makanan',
      date: '2024-01-03T11:00:00',
      score: 0,
      maxScore: 100,
      status: 'missed',
      duration: null
    }
  ];

  // Mock activity log
  const activityLog = [
    {
      id: '1',
      action: 'Login',
      description: 'User logged into the system',
      timestamp: '2024-01-15T09:05:00',
      ipAddress: '192.168.1.100'
    },
    {
      id: '2',
      action: 'Exam Completed',
      description: 'Completed "Ujian Tengah Semester - Algoritma"',
      timestamp: '2024-01-10T11:45:30',
      ipAddress: '192.168.1.100'
    },
    {
      id: '3',
      action: 'Profile Updated',
      description: 'Updated phone number',
      timestamp: '2024-01-08T16:20:00',
      ipAddress: '192.168.1.100'
    },
    {
      id: '4',
      action: 'Login',
      description: 'User logged into the system',
      timestamp: '2024-01-08T14:00:00',
      ipAddress: '192.168.1.100'
    }
  ];

  const formatDateTime = (dateString: string) => {
    return new Date(dateString).toLocaleString('id-ID', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('id-ID', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const getRoleBadge = (role: string) => {
    const roleConfig = {
      admin: { label: 'Admin', className: 'bg-purple-100 text-purple-800' },
      student: { label: 'Mahasiswa', className: 'bg-blue-100 text-blue-800' }
    };

    const config = roleConfig[role as keyof typeof roleConfig] || roleConfig.student;
    
    return (
      <span className={`px-3 py-1 rounded-full text-sm font-medium ${config.className}`}>
        {config.label}
      </span>
    );
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      active: { label: 'Aktif', className: 'bg-green-100 text-green-800' },
      inactive: { label: 'Tidak Aktif', className: 'bg-gray-100 text-gray-800' },
      suspended: { label: 'Ditangguhkan', className: 'bg-red-100 text-red-800' }
    };

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.inactive;
    
    return (
      <span className={`px-3 py-1 rounded-full text-sm font-medium ${config.className}`}>
        {config.label}
      </span>
    );
  };

  const getExamStatusBadge = (status: string) => {
    const statusConfig = {
      completed: { label: 'Selesai', className: 'bg-green-100 text-green-800' },
      in_progress: { label: 'Sedang Berlangsung', className: 'bg-yellow-100 text-yellow-800' },
      missed: { label: 'Tidak Hadir', className: 'bg-red-100 text-red-800' }
    };

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.completed;
    
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${config.className}`}>
        {config.label}
      </span>
    );
  };

  const getScoreColor = (score: number, maxScore: number) => {
    const percentage = (score / maxScore) * 100;
    if (percentage >= 80) return 'text-green-600';
    if (percentage >= 60) return 'text-yellow-600';
    return 'text-red-600';
  };

  const handleToggleStatus = () => {
    const newStatus = user.status === 'active' ? 'inactive' : 'active';
    alert(`Status pengguna berhasil diubah menjadi ${newStatus === 'active' ? 'aktif' : 'tidak aktif'}`);
  };

  const handleResetPassword = () => {
    if (confirm('Apakah Anda yakin ingin mereset password pengguna ini?')) {
      alert('Password berhasil direset. Password baru telah dikirim ke email pengguna.');
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Detail Pengguna</h1>
          <p className="text-gray-600 mt-1">Informasi lengkap dan aktivitas pengguna</p>
        </div>
        <div className="flex items-center space-x-3">
          <Link
            href={`/admin/users/${userId}/edit`}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            Edit Pengguna
          </Link>
          <Link
            href="/admin/users"
            className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
          >
            ← Kembali
          </Link>
        </div>
      </div>

      {/* User Profile Card */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="flex items-start space-x-6">
          <div className="flex-shrink-0">
            <div className="h-24 w-24 rounded-full bg-gray-300 flex items-center justify-center">
              <span className="text-2xl font-bold text-gray-700">
                {user.name.charAt(0).toUpperCase()}
              </span>
            </div>
          </div>
          
          <div className="flex-1">
            <div className="flex items-center space-x-4 mb-4">
              <h2 className="text-2xl font-bold text-gray-900">{user.name}</h2>
              {getRoleBadge(user.role)}
              {getStatusBadge(user.status)}
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
              <div>
                <span className="text-gray-500">Email:</span>
                <span className="ml-2 text-gray-900">{user.email}</span>
              </div>
              {user.role === 'student' && (
                <>
                  <div>
                    <span className="text-gray-500">NIM:</span>
                    <span className="ml-2 text-gray-900">{user.studentId}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">Kelas:</span>
                    <span className="ml-2 text-gray-900">{user.class}</span>
                  </div>
                </>
              )}
              <div>
                <span className="text-gray-500">Telepon:</span>
                <span className="ml-2 text-gray-900">{user.phone || '-'}</span>
              </div>
              <div>
                <span className="text-gray-500">Bergabung:</span>
                <span className="ml-2 text-gray-900">{formatDate(user.createdAt)}</span>
              </div>
              <div>
                <span className="text-gray-500">Login Terakhir:</span>
                <span className="ml-2 text-gray-900">{formatDateTime(user.lastLogin)}</span>
              </div>
            </div>
          </div>

          <div className="flex flex-col space-y-2">
            <button
              onClick={handleToggleStatus}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                user.status === 'active'
                  ? 'bg-red-100 text-red-700 hover:bg-red-200'
                  : 'bg-green-100 text-green-700 hover:bg-green-200'
              }`}
            >
              {user.status === 'active' ? 'Nonaktifkan' : 'Aktifkan'}
            </button>
            <button
              onClick={handleResetPassword}
              className="px-4 py-2 bg-orange-100 text-orange-700 rounded-lg text-sm font-medium hover:bg-orange-200 transition-colors"
            >
              Reset Password
            </button>
          </div>
        </div>
      </div>

      {/* Statistics (for students) */}
      {user.role === 'student' && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="text-2xl font-bold text-blue-600">{user.totalExams}</div>
            <div className="text-sm text-gray-600">Total Ujian</div>
          </div>
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="text-2xl font-bold text-green-600">{user.completedExams}</div>
            <div className="text-sm text-gray-600">Ujian Selesai</div>
          </div>
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="text-2xl font-bold text-orange-600">{user.totalExams - user.completedExams}</div>
            <div className="text-sm text-gray-600">Ujian Terlewat</div>
          </div>
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
            <div className="text-2xl font-bold text-purple-600">{user.averageScore.toFixed(1)}</div>
            <div className="text-sm text-gray-600">Rata-rata Nilai</div>
          </div>
        </div>
      )}

      {/* Tabs */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200">
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6">
            <button
              onClick={() => setActiveTab('overview')}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'overview'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              Informasi Umum
            </button>
            {user.role === 'student' && (
              <button
                onClick={() => setActiveTab('exams')}
                className={`py-4 px-1 border-b-2 font-medium text-sm ${
                  activeTab === 'exams'
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                Riwayat Ujian
              </button>
            )}
            <button
              onClick={() => setActiveTab('activity')}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'activity'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              Log Aktivitas
            </button>
          </nav>
        </div>

        <div className="p-6">
          {/* Overview Tab */}
          {activeTab === 'overview' && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">Informasi Personal</h3>
                  <div className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-gray-500">Tanggal Lahir:</span>
                      <span className="text-gray-900">{user.dateOfBirth ? formatDate(user.dateOfBirth) : '-'}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">Jenis Kelamin:</span>
                      <span className="text-gray-900">
                        {user.gender === 'male' ? 'Laki-laki' : user.gender === 'female' ? 'Perempuan' : '-'}
                      </span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">Alamat:</span>
                      <span className="text-gray-900 text-right">{user.address || '-'}</span>
                    </div>
                  </div>
                </div>

                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">Informasi Akun</h3>
                  <div className="space-y-3">
                    <div className="flex justify-between">
                      <span className="text-gray-500">ID Pengguna:</span>
                      <span className="text-gray-900">{user.id}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">Tanggal Dibuat:</span>
                      <span className="text-gray-900">{formatDateTime(user.createdAt)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">Status Akun:</span>
                      <span>{getStatusBadge(user.status)}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Exams Tab */}
          {activeTab === 'exams' && user.role === 'student' && (
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Riwayat Ujian</h3>
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Ujian
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Tanggal
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Nilai
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Durasi
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Status
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {examHistory.map((exam) => (
                      <tr key={exam.id} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm font-medium text-gray-900">{exam.title}</div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {formatDateTime(exam.date)}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {exam.status === 'completed' ? (
                            <span className={`text-sm font-medium ${getScoreColor(exam.score, exam.maxScore)}`}>
                              {exam.score}/{exam.maxScore} ({((exam.score / exam.maxScore) * 100).toFixed(1)}%)
                            </span>
                          ) : (
                            <span className="text-sm text-gray-400">-</span>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                          {exam.duration || '-'}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {getExamStatusBadge(exam.status)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Activity Tab */}
          {activeTab === 'activity' && (
            <div>
              <h3 className="text-lg font-semibold text-gray-900 mb-4">Log Aktivitas</h3>
              <div className="space-y-4">
                {activityLog.map((activity) => (
                  <div key={activity.id} className="flex items-start space-x-4 p-4 bg-gray-50 rounded-lg">
                    <div className="flex-shrink-0 w-2 h-2 bg-blue-500 rounded-full mt-2"></div>
                    <div className="flex-1">
                      <div className="flex items-center justify-between">
                        <h4 className="text-sm font-medium text-gray-900">{activity.action}</h4>
                        <span className="text-xs text-gray-500">{formatDateTime(activity.timestamp)}</span>
                      </div>
                      <p className="text-sm text-gray-600 mt-1">{activity.description}</p>
                      <p className="text-xs text-gray-400 mt-1">IP: {activity.ipAddress}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default UserDetailPage;