'use client';
import React, { useEffect, useState } from 'react';
import api from '@/lib/api';

interface User {
  id: string;
  email: string;
  role: string;
  created_at: string;
}

export default function AdminPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchUsers = async () => {
    try {
      const res = await api.get('/admin/users');
      setUsers(res.data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  const handleTierChange = async (userId: string, newRole: string) => {
    try {
      await api.put(`/admin/users/${userId}/tier`, { role: newRole });
      alert('User tier updated successfully!');
      fetchUsers();
    } catch (err) {
      console.error(err);
      alert('Failed to update tier');
    }
  };

  return (
    <div className="p-10 max-w-6xl mx-auto font-sans">
      <div className="mb-10">
        <h1 className="text-4xl font-extrabold text-gray-900 tracking-tight">User Management</h1>
        <p className="text-gray-500 mt-2 font-medium">Manage user subscriptions, trial statuses, and roles.</p>
      </div>

      <div className="bg-white rounded-2xl shadow-xl shadow-gray-200/50 border border-gray-200 overflow-hidden">
        
        <div className="p-6 border-b border-gray-100 bg-gray-50/50 flex justify-between items-center">
           <h3 className="text-lg font-bold text-gray-800">Platform Users</h3>
           <span className="bg-indigo-100 text-indigo-700 font-bold px-3 py-1 rounded-full text-xs">{users.length} Total</span>
        </div>

        {loading ? (
          <div className="p-10 text-center text-gray-500 font-medium">Loading users...</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="border-b border-gray-200 bg-gray-50">
                  <th className="px-6 py-4 text-xs font-bold text-gray-500 uppercase tracking-widest">Account / Email</th>
                  <th className="px-6 py-4 text-xs font-bold text-gray-500 uppercase tracking-widest">Status / Tier</th>
                  <th className="px-6 py-4 text-xs font-bold text-gray-500 uppercase tracking-widest">Joined</th>
                  <th className="px-6 py-4 text-xs font-bold text-gray-500 uppercase tracking-widest text-right">Admin Action</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 bg-white">
                {users.map((user) => (
                  <tr key={user.id} className="hover:bg-indigo-50/30 transition-colors">
                    <td className="px-6 py-5">
                      <div className="flex items-center gap-3">
                         <div className="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-100 to-purple-100 flex items-center justify-center border border-indigo-200 text-indigo-700 font-bold">
                           {user.email.charAt(0).toUpperCase()}
                         </div>
                         <div className="font-bold text-gray-900">{user.email}</div>
                      </div>
                    </td>
                    <td className="px-6 py-5">
                      <span className={`px-3 py-1 inline-flex text-xs font-bold rounded-full border shadow-sm
                        ${user.role === 'pro' ? 'bg-green-50 text-green-700 border-green-200' : 
                          user.role === 'enterprise' ? 'bg-purple-50 text-purple-700 border-purple-200' : 
                          user.role === 'free_trial' ? 'bg-amber-50 text-amber-700 border-amber-200' : 
                          'bg-gray-50 text-gray-700 border-gray-200'}`}>
                        {user.role === 'free_trial' ? 'FREE TRIAL' : user.role.toUpperCase()}
                      </span>
                    </td>
                    <td className="px-6 py-5 text-sm font-medium text-gray-500">
                      {new Date(user.created_at).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}
                    </td>
                    <td className="px-6 py-5 text-right">
                      <select 
                        value={user.role}
                        onChange={(e) => handleTierChange(user.id, e.target.value)}
                        className="bg-white border-gray-300 rounded-lg shadow-sm py-2 px-3 border focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 text-sm font-medium text-gray-700 hover:border-indigo-400 transition-colors cursor-pointer"
                      >
                        <option value="free">Free Tier</option>
                        <option value="free_trial">14-Day Trial</option>
                        <option value="pro">Pro Tier</option>
                        <option value="enterprise">Enterprise</option>
                      </select>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
