'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import UserModal from './UserModal';
import { authFetch } from '@/lib/api';
import Image from 'next/image';

async function fetchUsers() {
  return authFetch('/api/admin/users');
}

export default function UsersList() {
  const [selectedUser, setSelectedUser] = useState(null);

  // TanStack Query implementation
  const { data: users = [], isLoading, isError, error } = useQuery({
    queryKey: ['admin-users'],
    queryFn: fetchUsers,
    onError: (err) => {
      console.error('Error fetching users:', err);
    }
  });

  if (isLoading) {
    return (
      <div className="p-4">
        <h1 className="text-2xl font-semibold mb-4">All Users</h1>
        <div className="animate-pulse space-y-4">
          <div className="h-12 bg-gray-200 rounded"></div>
          {[...Array(5)].map((_, i) => (
            <div key={i} className="h-16 bg-gray-100 rounded"></div>
          ))}
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="p-4">
        <h1 className="text-2xl font-semibold mb-4">All Users</h1>
        <div className="bg-red-100 border-l-4 border-red-500 text-red-700 p-4">
          <p>Error loading users: {error.message}</p>
          <button
            onClick={() => window.location.reload()}
            className="mt-2 bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 text-xs"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4 p-4">
      <h1 className="text-2xl font-semibold">All Users</h1>

      <div className="overflow-x-auto shadow-md rounded-lg">
        <table className="min-w-full bg-white text-sm">
          <thead>
            <tr className="bg-gray-100 text-left text-xs uppercase text-gray-600 tracking-wider">
              <th className="px-4 py-3">#</th>
              <th className="px-4 py-3">Name</th>
              <th className="px-4 py-3">Email</th>
              <th className="px-4 py-3">Role</th>
              <th className="px-4 py-3">Status</th>
              <th className='px-4 py-3'>Email Verified</th>
              <th className="px-4 py-3">Date Created</th>
              <th className="px-4 py-3">Actions</th>
            </tr>
          </thead>
          <tbody className="text-gray-700">
            {users.map((user, index) => (
              <tr key={user.id} className="border-t">
                <td className="px-4 py-3">{index + 1}</td>
                <td className="px-4 py-3 font-medium">
                  <div className="flex items-center">
                    {user.avatar && (
                      <Image
                        src={user.avatar}
                        alt={user.firstName}
                        width={32}
                        height={32}
                        className="w-8 h-8 rounded-full mr-3 object-cover"
                      />
                    )}
                    {user.firstName} {user.lastName}
                  </div>
                </td>
                <td className="px-4 py-3">{user.email}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-1 rounded-full text-xs ${user.role === 'admin' ? 'bg-purple-100 text-purple-800' :
                    user.role === 'doctor' ? 'bg-blue-100 text-blue-800' :
                      user.role === 'pharmacy' ? 'bg-orange-100 text-orange-800' :
                        'bg-green-100 text-green-800'
                    }`}>
                    {user.role}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-1 rounded-full text-xs font-semibold ${user.status === 'Active' ? 'bg-green-100 text-green-700' :
                    user.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                      'bg-green-100 text-green-700'
                    }`}>
                    {user.status}
                  </span>
                </td>
                <td className="px-4 py-3">
                  {user.isVerified ? (
                    <span className="text-green-500 font-semibold">Yes</span>
                  ) : (
                    <span className="text-red-500 font-semibold">No</span>
                  )}
                </td>
                <td className="px-4 py-3">
                  {new Date(user.createdAt).toLocaleDateString('en-UK', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit'
                  })}
                </td>
                <td className="px-4 py-3 space-x-2">
                  <button
                    onClick={() => setSelectedUser(user)}
                    className="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 text-xs"
                  >
                    View
                  </button>
                  {user.status === 'pending' && (
                    <button
                      onClick={() => handleVerify(user.id)}
                      className="bg-green-500 text-white px-3 py-1 rounded hover:bg-green-600 text-xs"
                    >
                      Verify
                    </button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {selectedUser && (
        <UserModal user={selectedUser} onClose={() => setSelectedUser(null)} />
      )}
    </div>
  );
}