'use client';

import { useEffect, useState, useCallback } from 'react';
import { adminService } from '@/services/admin.service';
import { useSystemConfig } from '@/hooks/useSystemConfig';
import type { UserProfile, PaginationMeta } from '@/types/admin.types';

// ===== ICONS =====
const SearchIcon = () => (
  <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
  </svg>
);

const BanIcon = () => (
  <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
  </svg>
);

const UnbanIcon = () => (
  <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
  </svg>
);

const DisableIcon = () => (
  <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
  </svg>
);

const EnableIcon = () => (
  <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
  </svg>
);

const VerifyIcon = () => (
  <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
  </svg>
);

const PasswordIcon = () => (
  <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
  </svg>
);

// ===== STATUS BADGE =====
function StatusBadge({ label, color }: { label: string; color: 'green' | 'red' | 'yellow' | 'blue' | 'gray' }) {
  const colors = {
    green: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30',
    red: 'bg-red-500/20 text-red-400 border-red-500/30',
    yellow: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
    blue: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
    gray: 'bg-slate-500/20 text-slate-400 border-slate-500/30',
  };
  return (
    <span className={`inline-flex rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase ${colors[color]}`}>
      {label}
    </span>
  );
}

// ===== USER MODAL =====
function UserDetailModal({ userId, onClose }: { userId: string; onClose: () => void }) {
  const [user, setUser] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [banReason, setBanReason] = useState('VIOLATION_OF_TERMS');
  const [banText, setBanText] = useState('');
  const [actionMsg, setActionMsg] = useState('');

  useEffect(() => {
    adminService.getUserById(userId).then((res) => {
      setUser(res);
      setLoading(false);
    });
  }, [userId]);

  const handleBan = async () => {
    try {
      const res = await adminService.banUser({ userId, reason: banReason, reasonText: banText || undefined });
      setUser(res);
      setActionMsg('User banned successfully');
    } catch (e: any) {
      setActionMsg(e?.response?.data?.message || 'Error banning user');
    }
  };

  const handleUnban = async () => {
    try {
      const res = await adminService.unbanUser({ userId, reason: 'Admin action' });
      setUser(res);
      setActionMsg('User unbanned successfully');
    } catch (e: any) {
      setActionMsg(e?.response?.data?.message || 'Error unbanning user');
    }
  };

  if (loading) return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
      <div className="animate-pulse rounded-xl bg-slate-900 p-6">Loading...</div>
    </div>
  );

  if (!user) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center overflow-y-auto bg-black/60 backdrop-blur-sm pt-10">
      <div className="relative w-full max-w-2xl rounded-2xl border border-white/10 bg-slate-900 p-6 shadow-2xl">
        <button onClick={onClose} className="absolute right-4 top-4 text-white/50 hover:text-white">&times;</button>

        <div className="flex items-start gap-4">
          <div className="flex h-16 w-16 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 text-xl font-bold text-white">
            {user.firstName?.[0] || user.email[0].toUpperCase()}
          </div>
          <div className="flex-1">
            <h2 className="text-xl font-bold text-white">{user.firstName} {user.lastName}</h2>
            <p className="text-sm text-slate-400">{user.email}</p>
            <div className="mt-2 flex flex-wrap gap-2">
              {user.isBanned && <StatusBadge label="Banned" color="red" />}
              {user.isDisabled && <StatusBadge label="Disabled" color="yellow" />}
              {user.isKycVerified && <StatusBadge label="KYC Verified" color="green" />}
              {!user.isKycVerified && <StatusBadge label="KYC Pending" color="gray" />}
              {user.isEmailVerified && <StatusBadge label="Email Verified" color="green" />}
              {user.role && <StatusBadge label={user.role.name} color="blue" />}
            </div>
          </div>
        </div>

        <div className="mt-6 grid grid-cols-2 gap-4">
          <div className="rounded-lg bg-white/5 p-3">
            <p className="text-xs text-slate-500">Phone</p>
            <p className="text-sm text-white">{user.phone || 'N/A'}</p>
          </div>
          <div className="rounded-lg bg-white/5 p-3">
            <p className="text-xs text-slate-500">2FA</p>
            <p className="text-sm text-white">{user.isTwoFactorEnabled ? 'Enabled' : 'Disabled'}</p>
          </div>
          <div className="rounded-lg bg-white/5 p-3">
            <p className="text-xs text-slate-500">Last Login</p>
            <p className="text-sm text-white">{user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString() : 'N/A'}</p>
          </div>
          <div className="rounded-lg bg-white/5 p-3">
            <p className="text-xs text-slate-500">Last IP</p>
            <p className="text-sm text-white">{user.lastLoginIp || 'N/A'}</p>
          </div>
          <div className="rounded-lg bg-white/5 p-3">
            <p className="text-xs text-slate-500">Joined</p>
            <p className="text-sm text-white">{new Date(user.createdAt).toLocaleDateString()}</p>
          </div>
          {user.wallet && (
            <div className="rounded-lg bg-white/5 p-3">
              <p className="text-xs text-slate-500">Wallet Balance</p>
              <p className="text-sm text-white">${Number(user.wallet.balance).toLocaleString()}</p>
              {user.wallet.isFrozen && <StatusBadge label="Frozen" color="red" />}
            </div>
          )}
        </div>

        {actionMsg && (
          <div className="mt-4 rounded-lg bg-blue-500/10 p-3 text-sm text-blue-400">{actionMsg}</div>
        )}

        <div className="mt-6 flex flex-wrap gap-3">
          {!user.isBanned ? (
            <div className="flex items-center gap-2">
              <select
                value={banReason}
                onChange={(e) => setBanReason(e.target.value)}
                className="rounded-lg bg-slate-800 px-3 py-2 text-xs text-white border border-slate-700"
              >
                <option value="VIOLATION_OF_TERMS">Terms Violation</option>
                <option value="FRAUDULENT_ACTIVITY">Fraud</option>
                <option value="SUSPICIOUS_BEHAVIOR">Suspicious Behavior</option>
                <option value="CHARGEBACK">Chargeback</option>
                <option value="KYC_VIOLATION">KYC Violation</option>
                <option value="SPAM">Spam</option>
                <option value="ABUSE">Abuse</option>
                <option value="OTHER">Other</option>
              </select>
              <input
                type="text"
                placeholder="Reason details..."
                value={banText}
                onChange={(e) => setBanText(e.target.value)}
                className="rounded-lg bg-slate-800 px-3 py-2 text-xs text-white border border-slate-700 w-40"
              />
              <button onClick={handleBan} className="rounded-lg bg-red-500/20 px-4 py-2 text-xs font-medium text-red-400 hover:bg-red-500/30">
                Ban User
              </button>
            </div>
          ) : (
            <button onClick={handleUnban} className="rounded-lg bg-emerald-500/20 px-4 py-2 text-xs font-medium text-emerald-400 hover:bg-emerald-500/30">
              Unban User
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ===== CONFIRMATION DIALOG =====
function ConfirmDialog({
  title,
  message,
  confirmLabel = 'Confirm',
  confirmColor = 'bg-red-500/20 text-red-400 hover:bg-red-500/30',
  onConfirm,
  onCancel,
}: {
  title: string;
  message: string;
  confirmLabel?: string;
  confirmColor?: string;
  onConfirm: () => void;
  onCancel: () => void;
}) {
  const [loading, setLoading] = useState(false);

  const handleConfirm = async () => {
    setLoading(true);
    try {
      await onConfirm();
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm">
      <div className="w-full max-w-md rounded-2xl border border-white/10 bg-slate-900 p-6 shadow-2xl">
        <h3 className="text-lg font-bold text-white">{title}</h3>
        <p className="mt-2 text-sm text-slate-400">{message}</p>
        <div className="mt-6 flex justify-end gap-3">
          <button
            onClick={onCancel}
            disabled={loading}
            className="rounded-lg bg-white/10 px-4 py-2 text-xs font-medium text-white hover:bg-white/20 disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            onClick={handleConfirm}
            disabled={loading}
            className={`rounded-lg px-4 py-2 text-xs font-medium ${confirmColor} disabled:opacity-50`}
          >
            {loading ? 'Processing...' : confirmLabel}
          </button>
        </div>
      </div>
    </div>
  );
}

// ===== TOAST =====
function Toast({ message, type, onClose }: { message: string; type: 'success' | 'error'; onClose: () => void }) {
  useEffect(() => {
    const timer = setTimeout(onClose, 4000);
    return () => clearTimeout(timer);
  }, [onClose]);

  return (
    <div className={`fixed right-4 top-4 z-[70] rounded-lg border px-4 py-3 text-sm shadow-xl ${
      type === 'success'
        ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-400'
        : 'border-red-500/30 bg-red-500/10 text-red-400'
    }`}>
      {message}
    </div>
  );
}

// ===== MAIN PAGE =====
export default function AdminUsersPage() {
  const sysConfig = useSystemConfig();
  const [users, setUsers] = useState<UserProfile[]>([]);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [filters, setFilters] = useState({ role: '', isBanned: '', isKycVerified: '', isDisabled: '' });
  const [page, setPage] = useState(1);
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [confirmAction, setConfirmAction] = useState<{ type: 'ban' | 'unban' | 'disable' | 'enable' | 'verifyKyc' | 'resetPassword'; userId: string } | null>(null);
  const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = { page, limit: 20 };
      if (search) params.search = search;
      if (filters.role) params.role = filters.role;
      if (filters.isBanned !== '') params.isBanned = filters.isBanned === 'true';
      if (filters.isKycVerified !== '') params.isKycVerified = filters.isKycVerified === 'true';
      if (filters.isDisabled !== '') params.isDisabled = filters.isDisabled === 'true';

      const res = await adminService.listUsers(params);
      setUsers(res.data);
      setMeta(res.meta);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, [page, search, filters]);

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

  const handleAction = async () => {
    if (!confirmAction) return;
    try {
      const { type, userId } = confirmAction;
      switch (type) {
        case 'ban':
          await adminService.banUser({ userId, reason: 'VIOLATION_OF_TERMS' });
          break;
        case 'unban':
          await adminService.unbanUser({ userId, reason: 'Admin action' });
          break;
        case 'disable':
          await adminService.disableUser(userId);
          break;
        case 'enable':
          await adminService.enableUser(userId);
          break;
        case 'verifyKyc':
          await adminService.verifyKyc({ userId, approved: true, notes: 'Verified by admin' });
          break;
        case 'resetPassword':
          await adminService.resetPassword({ userId, newPassword: sysConfig.defaultTempPassword });
          break;
      }
      setToast({ message: `Action ${type} completed successfully`, type: 'success' });
      fetchUsers();
    } catch (e: any) {
      setToast({ message: e?.response?.data?.message || `Failed to perform action`, type: 'error' });
    } finally {
      setConfirmAction(null);
    }
  };

  const handleActionClick = (e: React.MouseEvent, type: 'ban' | 'unban' | 'disable' | 'enable' | 'verifyKyc' | 'resetPassword', userId: string) => {
    e.stopPropagation();
    setConfirmAction({ type, userId });
  };

  return (
    <div className="space-y-6">
      {toast && <Toast message={toast.message} type={toast.type} onClose={() => setToast(null)} />}
      {confirmAction && (
        <ConfirmDialog
          title={`Confirm ${confirmAction.type.replace(/([A-Z])/g, ' $1').trim()}`}
          message={`Are you sure you want to ${confirmAction.type.replace(/([A-Z])/g, ' $1').trim().toLowerCase()} this user? This action will affect the user account.`}
          confirmLabel={confirmAction.type === 'resetPassword' ? 'Reset Password' : confirmAction.type === 'verifyKyc' ? 'Verify KYC' : confirmAction.type.charAt(0).toUpperCase() + confirmAction.type.slice(1)}
          confirmColor={
            confirmAction.type === 'enable' || confirmAction.type === 'unban' || confirmAction.type === 'verifyKyc'
              ? 'bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30'
              : 'bg-red-500/20 text-red-400 hover:bg-red-500/30'
          }
          onConfirm={handleAction}
          onCancel={() => setConfirmAction(null)}
        />
      )}

      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">User Management</h1>
          <p className="mt-1 text-sm text-white/50">Manage, search, ban/unban users</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={fetchUsers} className="rounded-lg bg-white/10 px-3 py-2 text-xs text-white/70 hover:bg-white/20">
            Refresh
          </button>
        </div>
      </div>

      {/* Search & Filters */}
      <div className="flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-[200px]">
          <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
            <SearchIcon />
          </div>
          <input
            type="text"
            placeholder="Search by email, name, phone..."
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(1); }}
            className="w-full rounded-lg border border-white/10 bg-white/5 py-2 pl-10 pr-4 text-sm text-white placeholder-slate-500 focus:border-indigo-500 focus:outline-none"
          />
        </div>
        <select value={filters.role} onChange={(e) => setFilters({ ...filters, role: e.target.value })} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white">
          <option value="">All Roles</option>
          <option value="USER">User</option>
          <option value="ADMIN">Admin</option>
          <option value="SUPER_ADMIN">Super Admin</option>
          <option value="SUPPORT_AGENT">Support Agent</option>
          <option value="MODERATOR">Moderator</option>
          <option value="ANALYST">Analyst</option>
        </select>
        <select value={filters.isBanned} onChange={(e) => setFilters({ ...filters, isBanned: e.target.value })} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white">
          <option value="">All Ban Status</option>
          <option value="true">Banned</option>
          <option value="false">Not Banned</option>
        </select>
        <select value={filters.isKycVerified} onChange={(e) => setFilters({ ...filters, isKycVerified: e.target.value })} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white">
          <option value="">All KYC</option>
          <option value="true">Verified</option>
          <option value="false">Unverified</option>
        </select>
      </div>

      {/* Table */}
      <div className="overflow-x-auto rounded-xl border border-white/5">
        <table className="w-full text-left text-sm">
          <thead className="border-b border-white/5 bg-white/[0.02]">
            <tr>
              <th className="px-4 py-3 font-medium text-slate-400">User</th>
              <th className="px-4 py-3 font-medium text-slate-400">Email</th>
              <th className="px-4 py-3 font-medium text-slate-400">Role</th>
              <th className="px-4 py-3 font-medium text-slate-400">Status</th>
              <th className="px-4 py-3 font-medium text-slate-400">KYC</th>
              <th className="px-4 py-3 font-medium text-slate-400">Joined</th>
              <th className="px-4 py-3 font-medium text-slate-400">Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-slate-500">Loading...</td></tr>
            ) : users.length === 0 ? (
              <tr><td colSpan={7} className="px-4 py-8 text-center text-slate-500">No users found</td></tr>
            ) : (
              users.map((user) => (
                <tr key={user.id} className="border-b border-white/5 transition-colors hover:bg-white/[0.02]">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 text-xs font-bold text-white">
                        {user.firstName?.[0] || user.email[0].toUpperCase()}
                      </div>
                      <span className="font-medium text-white">{user.firstName} {user.lastName}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-slate-300">{user.email}</td>
                  <td className="px-4 py-3">
                    <StatusBadge label={user.role?.name || 'USER'} color={user.role?.name === 'ADMIN' ? 'blue' : user.role?.name === 'SUPER_ADMIN' ? 'yellow' : 'gray'} />
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1 flex-wrap">
                      {user.isBanned && <StatusBadge label="Banned" color="red" />}
                      {user.isDisabled && <StatusBadge label="Disabled" color="yellow" />}
                      {!user.isBanned && !user.isDisabled && <StatusBadge label="Active" color="green" />}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    {user.isKycVerified ? <StatusBadge label="Verified" color="green" /> : <StatusBadge label="Pending" color="gray" />}
                  </td>
                  <td className="px-4 py-3 text-xs text-slate-400">{new Date(user.createdAt).toLocaleDateString()}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <button
                        onClick={(e) => { e.stopPropagation(); handleActionClick(e, 'ban', user.id); }}
                        className="rounded p-1.5 text-red-400 hover:bg-red-500/20 disabled:opacity-50"
                        title="Ban User"
                        disabled={user.isBanned}
                      >
                        <BanIcon />
                      </button>
                      <button
                        onClick={(e) => { e.stopPropagation(); handleActionClick(e, 'unban', user.id); }}
                        className="rounded p-1.5 text-emerald-400 hover:bg-emerald-500/20 disabled:opacity-50"
                        title="Unban User"
                        disabled={!user.isBanned}
                      >
                        <UnbanIcon />
                      </button>
                      <button
                        onClick={(e) => { e.stopPropagation(); handleActionClick(e, 'disable', user.id); }}
                        className="rounded p-1.5 text-amber-400 hover:bg-amber-500/20 disabled:opacity-50"
                        title="Disable User"
                        disabled={user.isDisabled}
                      >
                        <DisableIcon />
                      </button>
                      <button
                        onClick={(e) => { e.stopPropagation(); handleActionClick(e, 'enable', user.id); }}
                        className="rounded p-1.5 text-green-400 hover:bg-green-500/20 disabled:opacity-50"
                        title="Enable User"
                        disabled={!user.isDisabled}
                      >
                        <EnableIcon />
                      </button>
                      <button
                        onClick={(e) => { e.stopPropagation(); handleActionClick(e, 'verifyKyc', user.id); }}
                        className="rounded p-1.5 text-blue-400 hover:bg-blue-500/20 disabled:opacity-50"
                        title="Verify KYC"
                        disabled={user.isKycVerified}
                      >
                        <VerifyIcon />
                      </button>
                      <button
                        onClick={(e) => { e.stopPropagation(); handleActionClick(e, 'resetPassword', user.id); }}
                        className="rounded p-1.5 text-slate-400 hover:bg-slate-500/20 disabled:opacity-50"
                        title="Reset Password"
                      >
                        <PasswordIcon />
                      </button>
                      <button
                        onClick={(e) => { e.stopPropagation(); setSelectedUserId(user.id); }}
                        className="rounded p-1.5 text-indigo-400 hover:bg-indigo-500/20"
                        title="View Details"
                      >
                        <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {meta && (
        <div className="flex items-center justify-between">
          <p className="text-xs text-slate-500">
            Showing {(meta.page - 1) * meta.limit + 1}-{Math.min(meta.page * meta.limit, meta.total)} of {meta.total}
          </p>
          <div className="flex gap-2">
            <button disabled={page <= 1} onClick={() => setPage(page - 1)} className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white disabled:opacity-30 hover:bg-white/10">
              Previous
            </button>
            <button disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)} className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white disabled:opacity-30 hover:bg-white/10">
              Next
            </button>
          </div>
        </div>
      )}

      {/* User Detail Modal */}
      {selectedUserId && <UserDetailModal userId={selectedUserId} onClose={() => { setSelectedUserId(null); fetchUsers(); }} />}
    </div>
  );
}
