'use client';

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

const UsersPage: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [roleFilter, setRoleFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');

  // Mock users data
  const users = [
    {
      id: '1',
      name: 'Chef Ahmad Fauzi',
      email: 'ahmad.fauzi@dapurmbg.com',
      role: 'admin',
      status: 'active',
      class: null,
      studentId: null,
      createdAt: '2024-01-01T10:00:00',
      lastLogin: '2024-01-15T09:30:00',
      totalExams: 5,
      avatar: null
    },
    {
      id: '2',
      name: 'Chef Siti Aminah',
      email: 'siti.aminah@dapurmbg.com',
      role: 'admin',
      status: 'active',
      class: null,
      studentId: null,
      createdAt: '2024-01-02T11:00:00',
      lastLogin: '2024-01-14T14:20:00',
      totalExams: 3,
      avatar: null
    },
    {
      id: '3',
      name: 'Andi Wijaya',
      email: 'andi.wijaya@trainee.dapurmbg.com',
      role: 'student',
      status: 'active',
      class: 'Batch-A-2024',
      studentId: 'MBG2024001',
      createdAt: '2024-01-05T08:00:00',
      lastLogin: '2024-01-15T09:05:00',
      totalExams: 12,
      avatar: null
    },
    {
      id: '4',
      name: 'Sari Indah',
      email: 'sari.indah@trainee.dapurmbg.com',
      role: 'student',
      status: 'active',
      class: 'Batch-A-2024',
      studentId: 'MBG2024002',
      createdAt: '2024-01-05T08:15:00',
      lastLogin: '2024-01-15T08:45:00',
      totalExams: 11,
      avatar: null
    },
    {
      id: '5',
      name: 'Budi Santoso',
      email: 'budi.santoso@trainee.dapurmbg.com',
      role: 'student',
      status: 'inactive',
      class: 'Batch-B-2024',
      studentId: 'MBG2024003',
      createdAt: '2024-01-06T09:00:00',
      lastLogin: '2024-01-10T16:30:00',
      totalExams: 8,
      avatar: null
    },
    {
      id: '6',
      name: 'Dewi Sartika',
      email: 'dewi.sartika@trainee.dapurmbg.com',
      role: 'student',
      status: 'active',
      class: 'Batch-B-2024',
      studentId: 'MBG2024004',
      createdAt: '2024-01-06T09:30:00',
      lastLogin: '2024-01-15T07:20:00',
      totalExams: 10,
      avatar: null
    },
    {
      id: '7',
      name: 'Rizki Pratama',
      email: 'rizki.pratama@trainee.dapurmbg.com',
      role: 'student',
      status: 'suspended',
      class: 'Batch-C-2024',
      studentId: 'MBG2024005',
      createdAt: '2024-01-07T10:00:00',
      lastLogin: '2024-01-12T13:45:00',
      totalExams: 6,
      avatar: null
    }
  ];

  // Filter users based on search and filters
  const filteredUsers = users.filter(user => {
    const matchesSearch = user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (user.studentId && user.studentId.toLowerCase().includes(searchTerm.toLowerCase()));
    
    const matchesRole = roleFilter === 'all' || user.role === roleFilter;
    const matchesStatus = statusFilter === 'all' || user.status === statusFilter;
    
    return matchesSearch && matchesRole && matchesStatus;
  });

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

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

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

  const handleDeleteUser = (userId: string, userName: string) => {
    if (confirm(`Apakah Anda yakin ingin menghapus pengguna "${userName}"?`)) {
      // Simulate delete
      alert('Pengguna berhasil dihapus');
    }
  };

  const handleToggleStatus = (userId: string, currentStatus: string) => {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    // Simulate status toggle
    alert(`Status pengguna berhasil diubah menjadi ${newStatus === 'active' ? 'aktif' : 'tidak aktif'}`);
  };

  // Statistics
  const totalUsers = users.length;
  const totalAdmins = users.filter(u => u.role === 'admin').length;
  const totalStudents = users.filter(u => u.role === 'student').length;
  const activeUsers = users.filter(u => u.status === 'active').length;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Manajemen Pengguna</h1>
          <p className="text-gray-600 mt-1">Kelola peserta dan admin sistem</p>
        </div>
        <Link
          href="/admin/users/create"
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          + Tambah Pengguna
        </Link>
      </div>

      {/* Statistics */}
      <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">{totalUsers}</div>
          <div className="text-sm text-gray-600">Total Pengguna</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">{totalAdmins}</div>
          <div className="text-sm text-gray-600">Admin</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">{totalStudents}</div>
          <div className="text-sm text-gray-600">Peserta Pelatihan</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">{activeUsers}</div>
          <div className="text-sm text-gray-600">Aktif</div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Cari Pengguna
            </label>
            <input
              type="text"
              placeholder="Nama, email, atau NIM..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Role
            </label>
            <select
              value={roleFilter}
              onChange={(e) => setRoleFilter(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="all">Semua Role</option>
              <option value="admin">Admin</option>
              <option value="student">Peserta Pelatihan</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Status
            </label>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="all">Semua Status</option>
              <option value="active">Aktif</option>
              <option value="inactive">Tidak Aktif</option>
              <option value="suspended">Ditangguhkan</option>
            </select>
          </div>

          <div className="flex items-end">
            <button
              onClick={() => {
                setSearchTerm('');
                setRoleFilter('all');
                setStatusFilter('all');
              }}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
            >
              Reset Filter
            </button>
          </div>
        </div>
      </div>

      {/* Users Table */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200">
        <div className="px-6 py-4 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900">
            Daftar Pengguna ({filteredUsers.length} dari {totalUsers})
          </h2>
        </div>

        <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">
                  Pengguna
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Role
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Kelas/NIM
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Login Terakhir
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Total Ujian
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Aksi
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredUsers.map((user) => (
                <tr key={user.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center">
                      <div className="flex-shrink-0 h-10 w-10">
                        <div className="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                          <span className="text-sm font-medium text-gray-700">
                            {user.name.charAt(0).toUpperCase()}
                          </span>
                        </div>
                      </div>
                      <div className="ml-4">
                        <div className="text-sm font-medium text-gray-900">{user.name}</div>
                        <div className="text-sm text-gray-500">{user.email}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {getRoleBadge(user.role)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    {getStatusBadge(user.status)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {user.role === 'student' ? (
                      <div>
                        <div>{user.class}</div>
                        <div className="text-xs text-gray-500">{user.studentId}</div>
                      </div>
                    ) : (
                      <span className="text-gray-400">-</span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {formatDateTime(user.lastLogin)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {user.totalExams}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div className="flex items-center space-x-2">
                      <Link
                        href={`/admin/users/${user.id}`}
                        className="text-blue-600 hover:text-blue-900"
                        title="Lihat Detail"
                      >
                        👁️
                      </Link>
                      <Link
                        href={`/admin/users/${user.id}/edit`}
                        className="text-green-600 hover:text-green-900"
                        title="Edit"
                      >
                        ✏️
                      </Link>
                      <button
                        onClick={() => handleToggleStatus(user.id, user.status)}
                        className="text-orange-600 hover:text-orange-900"
                        title={user.status === 'active' ? 'Nonaktifkan' : 'Aktifkan'}
                      >
                        {user.status === 'active' ? '⏸️' : '▶️'}
                      </button>
                      <button
                        onClick={() => handleDeleteUser(user.id, user.name)}
                        className="text-red-600 hover:text-red-900"
                        title="Hapus"
                      >
                        🗑️
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {filteredUsers.length === 0 && (
            <div className="text-center py-12">
              <div className="text-gray-500">
                Tidak ada pengguna yang ditemukan dengan kriteria pencarian tersebut.
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Bulk Actions */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Aksi Massal</h3>
        <div className="flex flex-wrap gap-4">
          <Link
            href="/admin/users/import"
            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
          >
            📥 Import Pengguna
          </Link>
          <button className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
            📤 Export Data
          </button>
          <button className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors">
            📧 Kirim Email Massal
          </button>
        </div>
      </div>
    </div>
  );
};

export default UsersPage;