import { useState, useEffect } from 'react';
import { Users, Mail, Plus, Trash2, Copy, Check, KeyRound } from 'lucide-react';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth';
import type { User, Invite } from '@/types';
import { cn } from '@/lib/utils';

export function AdminPage() {
  const { user: currentUser } = useAuthStore();
  const [users, setUsers] = useState<User[]>([]);
  const [invites, setInvites] = useState<Invite[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'users' | 'invites'>('users');
  
  // Invite form
  const [showInviteForm, setShowInviteForm] = useState(false);
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteName, setInviteName] = useState('');
  const [inviteRole, setInviteRole] = useState<'admin' | 'user'>('user');
  const [inviteError, setInviteError] = useState('');
  const [inviteUrl, setInviteUrl] = useState('');
  const [copied, setCopied] = useState(false);
  
  useEffect(() => {
    loadData();
  }, []);
  
  const loadData = async () => {
    setIsLoading(true);
    try {
      const [usersData, invitesData] = await Promise.all([
        api.getUsers(),
        api.getInvites(),
      ]);
      setUsers(usersData);
      setInvites(invitesData);
    } catch (error) {
      console.error('Failed to load admin data:', error);
    } finally {
      setIsLoading(false);
    }
  };
  
  const handleCreateInvite = async (e: React.FormEvent) => {
    e.preventDefault();
    setInviteError('');
    
    try {
      const result = await api.createInvite({ email: inviteEmail, name: inviteName, role: inviteRole });
      setInviteUrl(result.setupUrl);
      setInvites([result, ...invites]);
      // Keep form open to show the URL
    } catch (error) {
      setInviteError(error instanceof Error ? error.message : 'Failed to create invite');
    }
  };
  
  const handleCopyUrl = () => {
    navigator.clipboard.writeText(inviteUrl);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  
  const handleChangeRole = async (userId: string, role: 'admin' | 'user' | 'service') => {
    try {
      await api.updateUserRole(userId, role);
      setUsers(users.map(u => u.id === userId ? { ...u, role } : u));
    } catch (error) {
      console.error('Failed to update role:', error);
    }
  };
  
  const [resetUserId, setResetUserId] = useState<string | null>(null);
  const [resetUrl, setResetUrl] = useState('');
  const [resetCopied, setResetCopied] = useState(false);
  const [resetLoading, setResetLoading] = useState(false);

  const handleGenerateResetLink = async (userId: string) => {
    setResetLoading(true);
    try {
      const result = await api.createPasswordReset(userId);
      setResetUserId(userId);
      setResetUrl(result.resetUrl);
    } catch (error) {
      console.error('Failed to generate reset link:', error);
    } finally {
      setResetLoading(false);
    }
  };

  const handleCopyResetUrl = () => {
    navigator.clipboard.writeText(resetUrl);
    setResetCopied(true);
    setTimeout(() => setResetCopied(false), 2000);
  };

  const dismissReset = () => {
    setResetUserId(null);
    setResetUrl('');
    setResetCopied(false);
  };

  const handleDeleteUser = async (userId: string) => {
    if (!confirm('Are you sure you want to delete this user?')) return;
    
    try {
      await api.deleteUser(userId);
      setUsers(users.filter(u => u.id !== userId));
    } catch (error) {
      console.error('Failed to delete user:', error);
    }
  };
  
  const handleDeleteInvite = async (inviteId: string) => {
    try {
      await api.deleteInvite(inviteId);
      setInvites(invites.filter(i => i.id !== inviteId));
    } catch (error) {
      console.error('Failed to delete invite:', error);
    }
  };
  
  const resetInviteForm = () => {
    setShowInviteForm(false);
    setInviteEmail('');
    setInviteName('');
    setInviteRole('user');
    setInviteError('');
    setInviteUrl('');
  };
  
  if (currentUser?.role !== 'admin') {
    return (
      <div className="text-center py-12">
        <p className="text-red-500">Access denied. Admin only.</p>
      </div>
    );
  }
  
  return (
    <div className="max-w-4xl mx-auto">
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Admin</h1>
      
      {/* Tabs */}
      <div className="flex gap-4 border-b border-gray-200 mb-6">
        <button
          onClick={() => setActiveTab('users')}
          className={cn(
            'pb-3 px-1 text-sm font-medium border-b-2 transition-colors',
            activeTab === 'users'
              ? 'border-blue-600 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          )}
        >
          <Users className="w-4 h-4 inline mr-2" />
          Users ({users.length})
        </button>
        <button
          onClick={() => setActiveTab('invites')}
          className={cn(
            'pb-3 px-1 text-sm font-medium border-b-2 transition-colors',
            activeTab === 'invites'
              ? 'border-blue-600 text-blue-600'
              : 'border-transparent text-gray-500 hover:text-gray-700'
          )}
        >
          <Mail className="w-4 h-4 inline mr-2" />
          Invites ({invites.filter(i => i.status === 'pending').length} pending)
        </button>
      </div>
      
      {isLoading ? (
        <div className="text-center py-12 text-gray-500">Loading...</div>
      ) : activeTab === 'users' ? (
        /* Users list */
        <div className="bg-white rounded-lg border border-gray-200">
          <table className="w-full">
            <thead>
              <tr className="border-b border-gray-200 text-left text-sm text-gray-500">
                <th className="px-4 py-3 font-medium">Name</th>
                <th className="px-4 py-3 font-medium">Email</th>
                <th className="px-4 py-3 font-medium">Role</th>
                <th className="px-4 py-3 font-medium">Joined</th>
                <th className="px-4 py-3"></th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => (
                <tr key={user.id} className="border-b border-gray-100 last:border-0">
                  <td className="px-4 py-3 text-sm font-medium text-gray-900">{user.name}</td>
                  <td className="px-4 py-3 text-sm text-gray-600">{user.email}</td>
                  <td className="px-4 py-3">
                    {user.id === currentUser?.id || user.role === 'service' ? (
                      <span className={cn(
                        'px-2 py-1 text-xs rounded-full',
                        user.role === 'admin' ? 'bg-purple-100 text-purple-700' :
                        user.role === 'service' ? 'bg-blue-100 text-blue-700' :
                        'bg-gray-100 text-gray-700'
                      )}>
                        {user.role}
                      </span>
                    ) : (
                      <select
                        value={user.role}
                        onChange={(e) => handleChangeRole(user.id, e.target.value as 'admin' | 'user')}
                        className={cn(
                          'px-2 py-1 text-xs rounded-full border-none cursor-pointer appearance-none',
                          user.role === 'admin' ? 'bg-purple-100 text-purple-700' :
                          'bg-gray-100 text-gray-700'
                        )}
                      >
                        <option value="user">user</option>
                        <option value="admin">admin</option>
                      </select>
                    )}
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-500">
                    {new Date(user.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      {user.id !== currentUser?.id && (
                        <>
                          {resetUserId === user.id ? (
                            <div className="flex items-center gap-1">
                              <span className="text-xs text-green-600">✓ Link generated!</span>
                              <button
                                onClick={handleCopyResetUrl}
                                className="text-xs px-2 py-1 bg-blue-600 text-white rounded flex items-center gap-1"
                              >
                                {resetCopied ? <Check className="w-3 h-3" /> : <Copy className="w-3 h-3" />}
                                {resetCopied ? 'Copied!' : 'Copy'}
                              </button>
                              <button
                                onClick={dismissReset}
                                className="text-xs px-1 py-1 text-gray-400 hover:text-gray-600"
                              >
                                ✕
                              </button>
                            </div>
                          ) : (
                            <button
                              onClick={() => handleGenerateResetLink(user.id)}
                              disabled={resetLoading}
                              className="p-1 text-gray-400 hover:text-blue-500"
                              title="Generate password reset link"
                            >
                              <KeyRound className="w-4 h-4" />
                            </button>
                          )}
                          {user.role !== 'service' && resetUserId !== user.id && (
                            <button
                              onClick={() => handleDeleteUser(user.id)}
                              className="p-1 text-gray-400 hover:text-red-500"
                              title="Delete user"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          )}
                        </>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        /* Invites */
        <div>
          {/* Create invite button/form */}
          {!showInviteForm ? (
            <button
              onClick={() => setShowInviteForm(true)}
              className="mb-4 btn btn-primary"
            >
              <Plus className="w-4 h-4" />
              Invite User
            </button>
          ) : (
            <div className="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
              <h3 className="font-medium text-gray-900 mb-4">Invite New User</h3>
              
              {inviteUrl ? (
                <div>
                  <p className="text-sm text-green-600 mb-2">✓ Invite created! Share this link:</p>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={inviteUrl}
                      readOnly
                      className="input flex-1 text-sm bg-white"
                    />
                    <button
                      onClick={handleCopyUrl}
                      className="btn btn-secondary"
                    >
                      {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
                    </button>
                  </div>
                  <button
                    onClick={resetInviteForm}
                    className="mt-3 text-sm text-gray-500 hover:text-gray-700"
                  >
                    Create another invite
                  </button>
                </div>
              ) : (
                <form onSubmit={handleCreateInvite} className="space-y-4">
                  {inviteError && (
                    <p className="text-sm text-red-500">{inviteError}</p>
                  )}
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Name</label>
                      <input
                        type="text"
                        value={inviteName}
                        onChange={(e) => setInviteName(e.target.value)}
                        required
                        className="input"
                        placeholder="John Doe"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                      <input
                        type="email"
                        value={inviteEmail}
                        onChange={(e) => setInviteEmail(e.target.value)}
                        required
                        className="input"
                        placeholder="john@example.com"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Role</label>
                      <select
                        value={inviteRole}
                        onChange={(e) => setInviteRole(e.target.value as 'admin' | 'user')}
                        className="input"
                      >
                        <option value="user">User</option>
                        <option value="admin">Admin</option>
                      </select>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <button type="submit" className="btn btn-primary">
                      Send Invite
                    </button>
                    <button type="button" onClick={resetInviteForm} className="btn btn-secondary">
                      Cancel
                    </button>
                  </div>
                </form>
              )}
            </div>
          )}
          
          {/* Invites list */}
          <div className="bg-white rounded-lg border border-gray-200">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200 text-left text-sm text-gray-500">
                  <th className="px-4 py-3 font-medium">Name</th>
                  <th className="px-4 py-3 font-medium">Email</th>
                  <th className="px-4 py-3 font-medium">Status</th>
                  <th className="px-4 py-3 font-medium">Expires</th>
                  <th className="px-4 py-3"></th>
                </tr>
              </thead>
              <tbody>
                {invites.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-4 py-8 text-center text-gray-500">
                      No invites yet
                    </td>
                  </tr>
                ) : (
                  invites.map((invite) => (
                    <tr key={invite.id} className="border-b border-gray-100 last:border-0">
                      <td className="px-4 py-3 text-sm font-medium text-gray-900">{invite.name}</td>
                      <td className="px-4 py-3 text-sm text-gray-600">{invite.email}</td>
                      <td className="px-4 py-3">
                        <span className={cn(
                          'px-2 py-1 text-xs rounded-full',
                          invite.status === 'accepted' ? 'bg-green-100 text-green-700' :
                          invite.status === 'expired' ? 'bg-red-100 text-red-700' :
                          'bg-yellow-100 text-yellow-700'
                        )}>
                          {invite.status}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm text-gray-500">
                        {new Date(invite.expiresAt).toLocaleDateString()}
                      </td>
                      <td className="px-4 py-3">
                        {invite.status === 'pending' && (
                          <button
                            onClick={() => handleDeleteInvite(invite.id)}
                            className="p-1 text-gray-400 hover:text-red-500"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
