'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
  Flame,
  UserPlus,
  Eye,
  EyeOff,
  Loader2,
  AlertTriangle,
  CheckCircle2,
  ArrowLeft,
  ShieldCheck,
  Info,
} from 'lucide-react';
import Link from 'next/link';

const PASSWORD_RULES = [
  { label: 'At least 8 characters', test: (p: string) => p.length >= 8 },
  { label: 'One uppercase letter (A–Z)', test: (p: string) => /[A-Z]/.test(p) },
  { label: 'One number (0–9)', test: (p: string) => /[0-9]/.test(p) },
  { label: 'One special character (!@#$…)', test: (p: string) => /[^A-Za-z0-9]/.test(p) },
];

export default function AdminSignupPage() {
  const router = useRouter();

  const [fullName, setFullName]     = useState('');
  const [email, setEmail]           = useState('');
  const [password, setPassword]     = useState('');
  const [signupKey, setSignupKey]   = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showKey, setShowKey]       = useState(false);
  const [error, setError]           = useState('');
  const [loading, setLoading]       = useState(false);
  const [success, setSuccess]       = useState(false);

  const passwordStrength = PASSWORD_RULES.filter((r) => r.test(password)).length;

  const strengthLabel = ['', 'Weak', 'Fair', 'Good', 'Strong'][passwordStrength];
  const strengthColor = [
    '',
    'bg-red-500',
    'bg-amber-500',
    'bg-yellow-400',
    'bg-emerald-500',
  ][passwordStrength];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const res = await fetch('/api/admin/signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fullName, email, password, signupKey }),
      });

      const data = await res.json();

      if (res.status === 429) {
        setError(data.error || 'Too many attempts. Please wait before trying again.');
        return;
      }

      if (!res.ok) {
        setError(data.error || 'Something went wrong. Please try again.');
        return;
      }

      setSuccess(true);
    } catch {
      setError('Network error. Please check your connection and try again.');
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return (
      <div className="min-h-screen bg-gray-950 flex items-center justify-center px-4">
        <div className="w-full max-w-sm text-center">
          <div className="w-16 h-16 bg-emerald-500/20 border border-emerald-500/30 rounded-full flex items-center justify-center mx-auto mb-6">
            <CheckCircle2 className="w-8 h-8 text-emerald-400" />
          </div>
          <h2 className="text-white font-bold text-2xl mb-3">Account Created!</h2>
          <p className="text-gray-400 text-sm leading-relaxed mb-2">
            Your account has been created with{' '}
            <span className="text-amber-400 font-semibold">pending</span> access.
          </p>
          <p className="text-gray-500 text-sm leading-relaxed mb-8">
            Ask an existing admin to promote your role to{' '}
            <code className="text-gray-300 bg-gray-800 px-1.5 py-0.5 rounded text-xs font-mono">
              admin
            </code>{' '}
            in the database before you can log in.
          </p>

          <div className="bg-gray-900 border border-gray-800 rounded-xl p-4 text-left mb-6">
            <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-3">
              Congratulations on becoming an signing up
            </p>
            <pre className="text-xs text-emerald-400 font-mono overflow-x-auto">
             An admin will have to grant you access.
             Reach out to an admin to access the dashboard. 
            </pre>
          </div>

          <Link
            href="/admin/login"
            className="inline-flex items-center gap-2 text-sm font-semibold text-orange-400 hover:text-orange-300 transition-colors"
          >
            <ArrowLeft className="w-4 h-4" />
            Go to Login
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-950 flex items-center justify-center px-4 py-12">
      <div className="w-full max-w-sm">
        {/* Logo */}
        <div className="flex items-center justify-center gap-2 mb-8">
          <div className="w-9 h-9 bg-orange-500 rounded-xl flex items-center justify-center">
            <Flame className="w-5 h-5 text-white" />
          </div>
          <span className="text-white font-black text-xl tracking-tight">
            TechTan Admin
          </span>
        </div>

        <div className="bg-gray-900 border border-gray-800 rounded-2xl p-8">
          <div className="mb-6">
            <div className="w-12 h-12 bg-gray-800 rounded-xl flex items-center justify-center mb-4">
              <UserPlus className="w-6 h-6 text-orange-400" />
            </div>
            <h1 className="text-white font-bold text-xl">Create Admin Account</h1>
            <p className="text-gray-400 text-sm mt-1">
              You&apos;ll need a signup key from an existing admin.
            </p>
          </div>

          {/* Role notice */}
          <div className="flex items-start gap-2.5 bg-amber-500/10 border border-amber-500/20 rounded-xl px-3.5 py-3 mb-5">
            <Info className="w-4 h-4 text-amber-400 mt-0.5 flex-shrink-0" />
            <p className="text-xs text-amber-300 leading-relaxed">
              New accounts are created with <strong>user</strong> role. An admin must
              promote you to <strong>admin</strong> in the database before you can log in.
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Full Name */}
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wide">
                Full Name
              </label>
              <input
                type="text"
                value={fullName}
                onChange={(e) => setFullName(e.target.value)}
                placeholder="Your full name"
                autoComplete="name"
                className="w-full px-3 py-3 rounded-md border border-gray-700 bg-gray-800 text-white text-sm placeholder-gray-500 outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-500 transition-all"
                required
              />
            </div>

            {/* Email */}
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wide">
                Email
              </label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="you@example.com"
                autoComplete="username"
                className="w-full px-3 py-3 rounded-md border border-gray-700 bg-gray-800 text-white text-sm placeholder-gray-500 outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-500 transition-all"
                required
              />
            </div>

            {/* Password */}
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wide">
                Password
              </label>
              <div className="relative">
                <input
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Create a strong password"
                  autoComplete="new-password"
                  className="w-full px-3 py-3 pr-10 rounded-md border border-gray-700 bg-gray-800 text-white text-sm placeholder-gray-500 outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-500 transition-all"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowPassword((p) => !p)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-200 transition-colors"
                  aria-label={showPassword ? 'Hide password' : 'Show password'}
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>

              {/* Password strength bar */}
              {password.length > 0 && (
                <div className="space-y-2 pt-1">
                  <div className="flex items-center gap-2">
                    <div className="flex-1 flex gap-1">
                      {[1, 2, 3, 4].map((n) => (
                        <div
                          key={n}
                          className={`h-1 flex-1 rounded-full transition-all duration-300 ${
                            passwordStrength >= n ? strengthColor : 'bg-gray-700'
                          }`}
                        />
                      ))}
                    </div>
                    <span className={`text-[10px] font-semibold ${
                      passwordStrength === 4 ? 'text-emerald-400' :
                      passwordStrength === 3 ? 'text-yellow-400' :
                      passwordStrength === 2 ? 'text-amber-400' : 'text-red-400'
                    }`}>
                      {strengthLabel}
                    </span>
                  </div>

                  <div className="grid grid-cols-2 gap-1">
                    {PASSWORD_RULES.map((rule) => {
                      const passes = rule.test(password);
                      return (
                        <div key={rule.label} className="flex items-center gap-1.5">
                          <div className={`w-1.5 h-1.5 rounded-full flex-shrink-0 transition-colors ${
                            passes ? 'bg-emerald-400' : 'bg-gray-600'
                          }`} />
                          <span className={`text-[10px] transition-colors ${
                            passes ? 'text-emerald-400' : 'text-gray-500'
                          }`}>
                            {rule.label}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>

            {/* Signup Key */}
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wide">
                Signup Key
              </label>
              <div className="relative">
                <div className="absolute left-3 top-1/2 -translate-y-1/2">
                  <ShieldCheck className="w-4 h-4 text-gray-500" />
                </div>
                <input
                  type={showKey ? 'text' : 'password'}
                  value={signupKey}
                  onChange={(e) => setSignupKey(e.target.value)}
                  placeholder="Enter the signup key"
                  autoComplete="off"
                  className="w-full pl-9 pr-10 py-3 rounded-md border border-gray-700 bg-gray-800 text-white text-sm placeholder-gray-500 outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-500 transition-all"
                  required
                />
                <button
                  type="button"
                  onClick={() => setShowKey((p) => !p)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-200 transition-colors"
                  aria-label={showKey ? 'Hide key' : 'Show key'}
                >
                  {showKey ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
    
            </div>

            {error && (
              <div className="flex items-start gap-2 bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-3 py-2.5 text-xs">
                <AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={loading || !fullName || !email || !password || !signupKey || passwordStrength < 4}
              className="w-full flex items-center justify-center gap-2 bg-orange-500 hover:bg-orange-600 disabled:bg-orange-500/40 disabled:cursor-not-allowed text-white font-semibold text-sm py-3 rounded-xl transition-colors"
            >
              {loading ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Creating Account…
                </>
              ) : (
                <>
                  <UserPlus className="w-4 h-4" />
                  Create Account
                </>
              )}
            </button>
          </form>
        </div>

        <div className="flex items-center justify-center gap-4 mt-6">
          <Link
            href="/admin/login"
            className="flex items-center gap-1.5 text-xs text-gray-500 hover:text-gray-300 transition-colors"
          >
            <ArrowLeft className="w-3.5 h-3.5" />
            Back to Login
          </Link>
        </div>

        <p className="text-center text-gray-600 text-xs mt-4">
          Ignite-100 Admin Panel · TechTan
        </p>
      </div>
    </div>
  );
}