import { useState, useEffect } from 'react';
import { Users, Mail, Plus, Trash2, Copy, Check, X, KeyRound, ChevronRight, Shield, ShieldAlert } 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 default 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');

  // User detail panel
  const [selectedUser, setSelectedUser] = useState<User | null>(null);

  // 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);

  // Password reset (in detail panel)
  const [resetUrl, setResetUrl] = useState('');
  const [resetCopied, setResetCopied] = useState(false);
  const [resetLoading, setResetLoading] = 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]);
    } 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') => {
    try {
      await api.updateUserRole(userId, role);
      const updated = users.map(u => u.id === userId ? { ...u, role } : u);
      setUsers(updated);
      if (selectedUser?.id === userId) {
        setSelectedUser({ ...selectedUser, role });
      }
    } catch (error) {
      console.error('Failed to update role:', error);
    }
  };

  const handleGenerateResetLink = async (userId: string) => {
    setResetLoading(true);
    try {
      const result = await api.createPasswordReset(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 closeUserPanel = () => {
    setSelectedUser(null);
    setResetUrl('');
    setResetCopied(false);
  };

  const handleDeleteUser = async (userId: string) => {
    if (!confirm('Are you sure you want to delete this user? All their data will be lost.')) return;
    try {
      await api.deleteUser(userId);
      setUsers(users.filter(u => u.id !== userId));
      if (selectedUser?.id === userId) closeUserPanel();
    } 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 dark:text-red-400 font-medium">Access denied. Admin only.</p>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto">
      <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-6">Admin</h1>

      {/* Tabs */}
      <div className="flex gap-4 border-b border-slate-200 dark:border-slate-700 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 dark:text-blue-400 dark:border-blue-400'
              : 'border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'
          )}
        >
          <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 dark:text-blue-400 dark:border-blue-400'
              : 'border-transparent text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'
          )}
        >
          <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-slate-500 dark:text-slate-400">Loading...</div>
      ) : activeTab === 'users' ? (
        <div className="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-x-auto">
          <table className="w-full min-w-[600px]">
            <thead>
              <tr className="border-b border-slate-200 dark:border-slate-700 text-left text-sm text-slate-500 dark:text-slate-400">
                <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 w-8"></th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => (
                <tr
                  key={user.id}
                  onClick={() => setSelectedUser(user)}
                  className="border-b border-slate-100 dark:border-slate-700 last:border-0 cursor-pointer hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors"
                >
                  <td className="px-4 py-3 text-sm font-medium text-slate-900 dark:text-slate-100">{user.name}</td>
                  <td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-300">{user.email}</td>
                  <td className="px-4 py-3">
                    <span className={cn(
                      'px-2 py-1 text-xs rounded-full',
                      user.role === 'admin' ? 'bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300' : 'bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300'
                    )}>
                      {user.role}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm text-slate-500 dark:text-slate-400">
                    {user.createdAt ? new Date(user.createdAt).toLocaleDateString() : '—'}
                  </td>
                  <td className="px-4 py-3">
                    <ChevronRight className="w-4 h-4 text-slate-400 dark:text-slate-500" />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div>
          {/* Create invite button/form */}
          {!showInviteForm ? (
            <button
              onClick={() => setShowInviteForm(true)}
              className="mb-4 inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
            >
              <Plus className="w-4 h-4" />
              Invite User
            </button>
          ) : (
            <div className="mb-6 p-4 bg-slate-50 dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700">
              <h3 className="font-medium text-slate-900 dark:text-slate-100 mb-4">Invite New User</h3>

              {inviteUrl ? (
                <div>
                  <p className="text-sm text-green-600 dark:text-green-400 mb-2">✓ Invite created! Share this link:</p>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={inviteUrl}
                      readOnly
                      className="flex-1 px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100"
                    />
                    <button
                      onClick={handleCopyUrl}
                      className="px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"
                    >
                      {copied ? <Check className="w-4 h-4 text-green-600 dark:text-green-400" /> : <Copy className="w-4 h-4 text-slate-600 dark:text-slate-300" />}
                    </button>
                  </div>
                  <button
                    onClick={resetInviteForm}
                    className="mt-3 text-sm text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300"
                  >
                    Create another invite
                  </button>
                </div>
              ) : (
                <form onSubmit={handleCreateInvite} className="space-y-4">
                  {inviteError && (
                    <p className="text-sm text-red-500 dark:text-red-400">{inviteError}</p>
                  )}
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Name</label>
                      <input
                        type="text"
                        value={inviteName}
                        onChange={(e) => setInviteName(e.target.value)}
                        required
                        className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="John Doe"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Email</label>
                      <input
                        type="email"
                        value={inviteEmail}
                        onChange={(e) => setInviteEmail(e.target.value)}
                        required
                        className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="john@example.com"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Role</label>
                      <select
                        value={inviteRole}
                        onChange={(e) => setInviteRole(e.target.value as 'admin' | 'user')}
                        className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg text-sm bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      >
                        <option value="user">User</option>
                        <option value="admin">Admin</option>
                      </select>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <button
                      type="submit"
                      className="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      Send Invite
                    </button>
                    <button
                      type="button"
                      onClick={resetInviteForm}
                      className="px-4 py-2 border border-slate-300 dark:border-slate-600 text-sm font-medium text-slate-700 dark:text-slate-300 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"
                    >
                      Cancel
                    </button>
                  </div>
                </form>
              )}
            </div>
          )}

          {/* Invites list */}
          <div className="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 overflow-x-auto">
            <table className="w-full min-w-[600px]">
              <thead>
                <tr className="border-b border-slate-200 dark:border-slate-700 text-left text-sm text-slate-500 dark:text-slate-400">
                  <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">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={6} className="px-4 py-8 text-center text-slate-500 dark:text-slate-400">
                      No invites yet
                    </td>
                  </tr>
                ) : (
                  invites.map((invite) => (
                    <tr key={invite.id} className="border-b border-slate-100 dark:border-slate-700 last:border-0">
                      <td className="px-4 py-3 text-sm font-medium text-slate-900 dark:text-slate-100">{invite.name}</td>
                      <td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-300">{invite.email}</td>
                      <td className="px-4 py-3">
                        <span className={cn(
                          'px-2 py-1 text-xs rounded-full',
                          invite.role === 'admin' ? 'bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300' : 'bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300'
                        )}>
                          {invite.role}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <span className={cn(
                          'px-2 py-1 text-xs rounded-full',
                          invite.status === 'accepted' ? 'bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300' :
                          invite.status === 'expired' ? 'bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300' :
                          'bg-yellow-100 dark:bg-yellow-900/50 text-yellow-700 dark:text-yellow-300'
                        )}>
                          {invite.status}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm text-slate-500 dark:text-slate-400">
                        {new Date(invite.expiresAt).toLocaleDateString()}
                      </td>
                      <td className="px-4 py-3">
                        {invite.status === 'pending' && (
                          <button
                            onClick={() => handleDeleteInvite(invite.id)}
                            className="p-1 text-slate-400 dark:text-slate-500 hover:text-red-500 dark:hover:text-red-400 transition-colors"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        )}
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* User Detail Slide-Over Panel */}
      {selectedUser && (
        <>
          {/* Backdrop */}
          <div
            className="fixed inset-0 bg-black/20 dark:bg-black/50 z-40"
            onClick={closeUserPanel}
          />
          {/* Panel */}
          <div className="fixed inset-y-0 right-0 w-full max-w-md bg-white dark:bg-slate-800 shadow-xl z-50 flex flex-col animate-in slide-in-from-right duration-200">
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 dark:border-slate-700">
              <h2 className="text-lg font-semibold text-slate-900 dark:text-slate-100">User Settings</h2>
              <button
                onClick={closeUserPanel}
                className="p-1 text-slate-400 dark:text-slate-500 hover:text-slate-600 dark:hover:text-slate-300 transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-6 space-y-6">
              {/* User info */}
              <div className="flex items-center gap-4">
                <div className="w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900/50 flex items-center justify-center text-blue-600 dark:text-blue-300 font-semibold text-lg">
                  {selectedUser.name?.charAt(0).toUpperCase() || '?'}
                </div>
                <div>
                  <h3 className="font-medium text-slate-900 dark:text-slate-100">{selectedUser.name}</h3>
                  <p className="text-sm text-slate-500 dark:text-slate-400">{selectedUser.email}</p>
                </div>
              </div>

              {/* Details */}
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Joined</label>
                  <p className="text-sm text-slate-600 dark:text-slate-300">
                    {selectedUser.createdAt ? new Date(selectedUser.createdAt).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) : '—'}
                  </p>
                </div>

                {/* Role */}
                <div>
                  <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Role</label>
                  {selectedUser.id === currentUser?.id ? (
                    <div className="flex items-center gap-2">
                      <span className="px-3 py-1.5 text-sm rounded-lg bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300 font-medium">
                        {selectedUser.role}
                      </span>
                      <span className="text-xs text-slate-400 dark:text-slate-500">(your account)</span>
                    </div>
                  ) : (
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleChangeRole(selectedUser.id, 'user')}
                        className={cn(
                          'flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border transition-colors',
                          selectedUser.role === 'user'
                            ? 'bg-slate-100 dark:bg-slate-700 border-slate-300 dark:border-slate-600 text-slate-900 dark:text-slate-100'
                            : 'border-slate-200 dark:border-slate-600 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-700'
                        )}
                      >
                        <Shield className="w-4 h-4" />
                        User
                      </button>
                      <button
                        onClick={() => handleChangeRole(selectedUser.id, 'admin')}
                        className={cn(
                          'flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium border transition-colors',
                          selectedUser.role === 'admin'
                            ? 'bg-purple-100 dark:bg-purple-900/50 border-purple-300 dark:border-purple-700 text-purple-700 dark:text-purple-300'
                            : 'border-slate-200 dark:border-slate-600 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-700'
                        )}
                      >
                        <ShieldAlert className="w-4 h-4" />
                        Admin
                      </button>
                    </div>
                  )}
                </div>
              </div>

              {/* Actions — only for non-self users */}
              {selectedUser.id !== currentUser?.id && (
                <div className="space-y-4 pt-4 border-t border-slate-200 dark:border-slate-700">
                  <h4 className="text-sm font-medium text-slate-700 dark:text-slate-300">Actions</h4>

                  {/* Password Reset */}
                  <div className="bg-slate-50 dark:bg-slate-700 rounded-lg p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <KeyRound className="w-4 h-4 text-slate-500 dark:text-slate-400" />
                      <span className="text-sm font-medium text-slate-700 dark:text-slate-300">Password Reset</span>
                    </div>
                    {resetUrl ? (
                      <div className="space-y-2">
                        <p className="text-xs text-green-600 dark:text-green-400">✓ Reset link generated</p>
                        <div className="flex gap-2">
                          <input
                            type="text"
                            value={resetUrl}
                            readOnly
                            className="flex-1 px-3 py-1.5 border border-slate-300 dark:border-slate-600 rounded-lg text-xs bg-white dark:bg-slate-800 text-slate-900 dark:text-slate-100 font-mono"
                          />
                          <button
                            onClick={handleCopyResetUrl}
                            className="px-3 py-1.5 bg-blue-600 text-white text-xs rounded-lg flex items-center gap-1 hover:bg-blue-700 transition-colors"
                          >
                            {resetCopied ? <Check className="w-3 h-3" /> : <Copy className="w-3 h-3" />}
                            {resetCopied ? 'Copied' : 'Copy'}
                          </button>
                        </div>
                      </div>
                    ) : (
                      <button
                        onClick={() => handleGenerateResetLink(selectedUser.id)}
                        disabled={resetLoading}
                        className="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 font-medium disabled:opacity-50"
                      >
                        {resetLoading ? 'Generating...' : 'Generate reset link'}
                      </button>
                    )}
                  </div>

                  {/* Delete User */}
                  <div className="bg-red-50 dark:bg-red-900/20 rounded-lg p-4">
                    <div className="flex items-center gap-2 mb-2">
                      <Trash2 className="w-4 h-4 text-red-500 dark:text-red-400" />
                      <span className="text-sm font-medium text-red-700 dark:text-red-300">Danger Zone</span>
                    </div>
                    <p className="text-xs text-red-600 dark:text-red-400 mb-3">Permanently delete this user and all their data.</p>
                    <button
                      onClick={() => handleDeleteUser(selectedUser.id)}
                      className="px-4 py-2 bg-red-600 text-white text-sm font-medium rounded-lg hover:bg-red-700 transition-colors"
                    >
                      Delete User
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
