'use client';

import React, { useState, useEffect } from 'react';
import { KeyRound, Search, Eye, Building, X } from 'lucide-react';
import SmartAuthCard from '@/components/ui/smartauth/SmartAuthCard';
import SmartAuthBadge from '@/components/ui/smartauth/SmartAuthBadge';
import SmartAuthButton from '@/components/ui/smartauth/SmartAuthButton';

export default function AdminApiUsersPage() {
  const [apiUsers, setApiUsers] = useState<any[]>([]);
  const [search, setSearch] = useState('');
  const [selectedUser, setSelectedUser] = useState<any>(null);

  useEffect(() => {
    async function fetchApiUsers() {
      try {
        const res = await fetch('/api/v1/admin/users?filter=API_USER');
        const data = await res.json();
        if (data.success) {
          setApiUsers(data.data.users || []);
        }
      } catch {}
    }
    fetchApiUsers();
  }, []);

  const filtered = apiUsers.filter((u) =>
    u.name?.toLowerCase().includes(search.toLowerCase()) ||
    u.company?.toLowerCase().includes(search.toLowerCase()) ||
    u.userCode?.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="space-y-7 animate-in fade-in duration-150">
      <div>
        <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight">API Users & Developers</h1>
        <p className="text-xs text-slate-500 mt-1">Manage approved corporate developers, API key allocations, and usage quotas.</p>
      </div>

      <SmartAuthCard title="API User Directory" subtitle={`Showing ${filtered.length} approved organizations`} headerIcon={KeyRound}>
        <div className="mb-4 max-w-sm">
          <input
            type="text"
            placeholder="Search company or User ID..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full px-4 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
          />
        </div>

        {filtered.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs">
              <thead>
                <tr className="border-b border-slate-100 text-slate-500 font-mono">
                  <th className="pb-3 font-semibold">Company / Developer</th>
                  <th className="pb-3 font-semibold">User ID</th>
                  <th className="pb-3 font-semibold">RC Number</th>
                  <th className="pb-3 font-semibold">Wallet Balance</th>
                  <th className="pb-3 font-semibold">Status</th>
                  <th className="pb-3 font-semibold text-right">Action</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filtered.map((u) => (
                  <tr key={u.id} className="hover:bg-slate-50 transition-colors">
                    <td className="py-3.5">
                      <span className="font-bold text-slate-900 block">{u.company || u.name}</span>
                      <span className="text-[11px] text-slate-500 font-mono">{u.email}</span>
                    </td>
                    <td className="py-3.5 font-mono font-bold text-emerald-800">{u.userCode}</td>
                    <td className="py-3.5 font-mono text-slate-600">{u.orgRcNumber || 'RC-Verified'}</td>
                    <td className="py-3.5 font-mono font-bold text-slate-900">
                      {Number(u.wallet?.unitsBalance ?? 0).toLocaleString()} Units
                    </td>
                    <td className="py-3.5"><SmartAuthBadge variant="success" size="sm">ACTIVE_API</SmartAuthBadge></td>
                    <td className="py-3.5 text-right">
                      <button
                        onClick={() => setSelectedUser(u)}
                        className="px-2.5 py-1 bg-slate-100 hover:bg-slate-200 text-slate-800 font-bold rounded-lg text-xs inline-flex items-center gap-1 transition-colors"
                      >
                        <Eye className="w-3.5 h-3.5" />
                        <span>Inspect</span>
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-xs text-slate-400 font-mono text-center py-6">No API users found.</p>
        )}
      </SmartAuthCard>

      {/* API User Inspection Drawer */}
      {selectedUser && (
        <div className="fixed inset-0 z-50 flex items-center justify-end bg-black/40 backdrop-blur-xs animate-in fade-in">
          <div className="w-full max-w-md h-full bg-white border-l border-slate-200 shadow-2xl p-6 overflow-y-auto space-y-6 animate-in slide-in-from-right duration-200">
            <div className="flex items-center justify-between border-b border-slate-100 pb-4">
              <div>
                <h3 className="text-base font-bold text-slate-900">API User Organization</h3>
                <p className="text-xs text-slate-500 font-mono">Developer Compliance Profile</p>
              </div>
              <button
                onClick={() => setSelectedUser(null)}
                className="p-1.5 rounded-xl text-slate-400 hover:text-slate-700 hover:bg-slate-100"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="space-y-4 text-xs">
              <div className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
                <div className="flex justify-between">
                  <span className="text-slate-500">Company:</span>
                  <span className="font-bold text-slate-900">{selectedUser.company || selectedUser.name}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">User ID:</span>
                  <span className="font-mono font-bold text-emerald-800">{selectedUser.userCode}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">Owner Email:</span>
                  <span className="font-mono text-slate-700">{selectedUser.email}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">RC Number:</span>
                  <span className="font-mono text-slate-700">{selectedUser.orgRcNumber || 'RC-104829'}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-500">Corporate Units:</span>
                  <span className="font-mono font-bold text-emerald-800">
                    {Number(selectedUser.wallet?.unitsBalance ?? 0).toLocaleString()} Units
                  </span>
                </div>
              </div>

              <div className="pt-4 flex justify-end">
                <SmartAuthButton variant="outline" size="md" onClick={() => setSelectedUser(null)}>
                  Close
                </SmartAuthButton>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
