'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  Wallet,
  Plus,
  LogOut,
  User,
  Shield,
  Sparkles,
  Check,
  X,
  RefreshCw,
} from 'lucide-react';

interface HeaderProps {
  user: any;
  walletBalance: number;
  onRefreshWallet?: () => void;
}

export default function Header({ user, walletBalance, onRefreshWallet }: HeaderProps) {
  const router = useRouter();
  const [topUpModalOpen, setTopUpModalOpen] = useState(false);
  const [topUpAmount, setTopUpAmount] = useState('10000');
  const [funding, setFunding] = useState(false);
  const [fundSuccess, setFundSuccess] = useState(false);

  const handleLogout = async () => {
    await fetch('/api/v1/auth/logout', { method: 'POST' });
    router.push('/login');
  };

  const handleTopUp = async () => {
    setFunding(true);
    try {
      const res = await fetch('/api/v1/wallet', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount: parseFloat(topUpAmount) }),
      });
      const data = await res.json();
      if (data.success) {
        setFundSuccess(true);
        if (onRefreshWallet) onRefreshWallet();
        setTimeout(() => {
          setFundSuccess(false);
          setTopUpModalOpen(false);
        }, 1200);
      }
    } catch {
      // Error handling
    } finally {
      setFunding(false);
    }
  };

  return (
    <header className="h-16 border-b border-slate-800 bg-[#070b14]/80 backdrop-blur-md px-6 flex items-center justify-between sticky top-0 z-30">
      {/* Left: Environment details */}
      <div className="flex items-center gap-3">
        <div className="hidden sm:flex items-center gap-2 px-2.5 py-1 rounded-md bg-emerald-500/10 border border-emerald-500/20 text-[11px] font-mono text-emerald-300">
          <span className="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>
          <span>Gateway: api.smartauth.ng</span>
        </div>
      </div>

      {/* Right: Wallet Balance & User Profile */}
      <div className="flex items-center gap-3">
        {/* Wallet Balance Chip */}
        <div className="flex items-center bg-slate-900 border border-slate-800 rounded-xl p-1 pl-3 shadow-inner">
          <div className="flex items-center gap-2 mr-3">
            <Wallet className="w-4 h-4 text-emerald-400" />
            <div className="flex flex-col">
              <span className="text-[10px] text-slate-400 font-medium">Units</span>
              <span className="text-xs font-bold text-white font-mono leading-none">
                {(walletBalance || 0).toLocaleString()} Units
              </span>
            </div>
          </div>
          <button
            onClick={() => setTopUpModalOpen(true)}
            className="px-2.5 py-1 bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-300 text-[11px] font-bold rounded-lg border border-emerald-500/40 transition-colors flex items-center gap-1"
          >
            <Plus className="w-3 h-3" />
            Fund Units
          </button>
        </div>

        {/* User Role & Name */}
        <div className="flex items-center gap-2.5 pl-3 border-l border-slate-800">
          <div className="w-8 h-8 rounded-lg bg-slate-800 border border-slate-700 flex items-center justify-center text-xs font-bold text-white uppercase">
            {user?.name ? user.name.slice(0, 2) : 'SA'}
          </div>
          <div className="hidden md:flex flex-col">
            <span className="text-xs font-bold text-white leading-tight">
              {user?.name || 'User'}
            </span>
            <span className="text-[10px] text-emerald-400 font-mono">
              {user?.role || 'STANDARD_USER'}
            </span>
          </div>

          <button
            onClick={handleLogout}
            title="Sign Out"
            className="p-2 text-slate-400 hover:text-rose-400 rounded-lg hover:bg-slate-900 transition-colors"
          >
            <LogOut className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Top Up Modal */}
      {topUpModalOpen && (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <div className="glass-panel w-full max-w-md rounded-2xl p-6 border border-slate-700 space-y-5 shadow-2xl animate-in fade-in zoom-in-95 duration-200">
            <div className="flex items-center justify-between border-b border-slate-800 pb-3">
              <div className="flex items-center gap-2">
                <Wallet className="w-5 h-5 text-emerald-400" />
                <h3 className="text-base font-bold text-white">Instant Sandbox Top Up</h3>
              </div>
              <button
                onClick={() => setTopUpModalOpen(false)}
                className="text-slate-400 hover:text-white p-1"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            <p className="text-xs text-slate-300">
              In Sandbox mode, you can generate instant mock test credit without making any real financial payment.
            </p>

            <div className="space-y-3">
              <label className="block text-xs font-semibold text-slate-300">Select Amount (NGN)</label>
              <div className="grid grid-cols-3 gap-2">
                {['5000', '10000', '50000'].map((amt) => (
                  <button
                    key={amt}
                    type="button"
                    onClick={() => setTopUpAmount(amt)}
                    className={`py-2 px-3 rounded-xl border text-xs font-mono font-bold transition-all ${
                      topUpAmount === amt
                        ? 'bg-emerald-500/20 text-emerald-300 border-emerald-500'
                        : 'bg-slate-900/80 text-slate-300 border-slate-800 hover:border-slate-700'
                    }`}
                  >
                    ₦{parseInt(amt).toLocaleString()}
                  </button>
                ))}
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-300 mb-1">Custom Amount</label>
                <input
                  type="number"
                  value={topUpAmount}
                  onChange={(e) => setTopUpAmount(e.target.value)}
                  className="w-full bg-slate-900 border border-slate-700 rounded-xl px-3.5 py-2 text-xs font-mono text-white focus:outline-none focus:border-emerald-500"
                />
              </div>
            </div>

            <div className="pt-2">
              <button
                onClick={handleTopUp}
                disabled={funding || fundSuccess}
                className="w-full py-3 bg-emerald-400 hover:bg-emerald-300 text-slate-900 font-bold text-xs rounded-xl shadow-lg shadow-emerald-500/20 transition-all flex items-center justify-center gap-2 disabled:opacity-50"
              >
                {funding ? (
                  <RefreshCw className="w-4 h-4 animate-spin" />
                ) : fundSuccess ? (
                  <Check className="w-4 h-4 text-slate-900" />
                ) : (
                  <Plus className="w-4 h-4" />
                )}
                {funding
                  ? 'Crediting Sandbox Wallet...'
                  : fundSuccess
                  ? 'Wallet Funded Successfully!'
                  : `Credit ₦${parseFloat(topUpAmount || '0').toLocaleString()} to Wallet`}
              </button>
            </div>
          </div>
        </div>
      )}
    </header>
  );
}
