"use client";

import { useState } from "react";
import { createClient } from "@/utils/supabase/client";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function Register() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [fullName, setFullName] = useState("");
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  
  const router = useRouter();
  const supabase = createClient();

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setErrorMsg(null);
    setSuccessMsg(null);

    const { data, error } = await supabase.auth.signUp({
      email,
      password,
      options: {
        data: { full_name: fullName }, 
      },
    });

    if (error) {
      setErrorMsg(error.message);
      setLoading(false);
    } else {
      if (data.session) {
        setSuccessMsg("Registration successful! Redirecting to login...");
        setTimeout(() => router.push("/login"), 3000);
      } else {
        setSuccessMsg("Account created! Please check your email for a verification link.");
      }
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col sm:justify-center items-center pt-6 sm:pt-0 bg-[#f3f4f6] selection:bg-indigo-500 selection:text-white">
      
      {/* Brand Logo Area */}
      <div className="mb-6">
        <Link href="/" className="flex flex-col items-center gap-2 group">
          <div className="w-12 h-12 bg-indigo-600 rounded-xl flex items-center justify-center shadow-lg shadow-indigo-200 group-hover:scale-105 transition-transform duration-200">
            <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
            </svg>
          </div>
          <h1 className="text-2xl font-bold tracking-tight text-gray-900">
            Omugwor<span className="text-indigo-600">Admin</span>
          </h1>
        </Link>
      </div>

      {/* Main Card */}
      <div className="w-full sm:max-w-md mt-6 px-6 py-8 bg-white shadow-xl shadow-gray-200/50 overflow-hidden sm:rounded-xl border border-gray-100">
        
        <h2 className="text-lg font-bold text-gray-900 mb-6">Create Admin Account</h2>

        {/* Status Messages */}
        {errorMsg && (
          <div className="mb-4 p-4 text-sm text-red-800 border border-red-100 rounded-lg bg-red-50 animate-in fade-in slide-in-from-top-1">
            <p className="font-medium">{errorMsg}</p>
          </div>
        )}

        {successMsg && (
          <div className="mb-4 p-4 text-sm text-green-800 border border-green-100 rounded-lg bg-green-50 animate-in fade-in slide-in-from-top-1 text-center">
            <p className="font-medium">{successMsg}</p>
          </div>
        )}

        <form onSubmit={handleRegister} className="space-y-5">
          {/* Full Name */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 ml-1">Full Name</label>
            <input
              type="text"
              required
              className="mt-1 block w-full px-4 py-3 bg-gray-50 border-gray-200 rounded-lg text-gray-900 focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 border outline-none transition-all duration-200"
              placeholder="John Doe"
              onChange={(e) => setFullName(e.target.value)}
            />
          </div>

          {/* Email */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 ml-1">Email Address</label>
            <input
              type="email"
              required
              className="mt-1 block w-full px-4 py-3 bg-gray-50 border-gray-200 rounded-lg text-gray-900 focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 border outline-none transition-all duration-200"
              placeholder="admin@omugwor.com"
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>

          {/* Password */}
          <div>
            <label className="block text-sm font-semibold text-gray-700 ml-1">Password</label>
            <input
              type="password"
              required
              className="mt-1 block w-full px-4 py-3 bg-gray-50 border-gray-200 rounded-lg text-gray-900 focus:bg-white focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 border outline-none transition-all duration-200"
              placeholder="••••••••"
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>

          {/* Action Button */}
          <button
            type="submit"
            disabled={loading}
            className="w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-bold text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-all duration-150 disabled:opacity-70"
          >
            {loading ? (
              <svg className="animate-spin h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
              </svg>
            ) : (
              "Register Admin"
            )}
          </button>

          <div className="text-center mt-4">
            <Link href="/login" className="text-sm font-medium text-indigo-600 hover:text-indigo-500 transition-colors">
              Already have an account? Sign In
            </Link>
          </div>
        </form>

        {/* Security Note */}
        <div className="mt-8 pt-6 border-t border-gray-100">
          <div className="flex gap-3 p-3 bg-amber-50 border border-amber-100 rounded-lg">
            <svg className="w-5 h-5 text-amber-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <p className="text-[11px] text-amber-800 leading-tight">
              <strong>Admin Policy:</strong> Registration alone does not grant dashboard access. 
              A head administrator must manually flag your profile as <code className="bg-amber-100 px-1 rounded">is_admin: true</code> in the database before you can log in.
            </p>
          </div>
        </div>
      </div>

      {/* Footer Branding */}
      <p className="mt-8 text-center text-xs text-gray-500 tracking-widest uppercase font-medium">
        Omugwor Systems &bull; Admin Enrollment
      </p>
    </div>
  );
}