"use client";
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import { createClient } from "@/lib/supabase/client";

export default function RegisterPage() {
  const router = useRouter();
  const supabase = createClient();

  const [fullName, setFullName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [checkingAuth, setCheckingAuth] = useState(true);

  useEffect(() => {
    supabase.auth.getUser().then(({ data }) => {
      if (data?.user) {
        router.replace("/account");
      } else {
        setCheckingAuth(false);
      }
    });
  }, []);

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!fullName.trim()) {
      setError("Please enter your full name.");
      return;
    }
    if (!email) {
      setError("Please enter your email address.");
      return;
    }
    if (password.length < 6) {
      setError("Password must be at least 6 characters.");
      return;
    }
    if (password !== confirmPassword) {
      setError("Passwords do not match.");
      return;
    }

    setLoading(true);
    try {
      const { error: signUpError } = await supabase.auth.signUp({
        email,
        password,
        options: {
          data: {
            full_name: fullName.trim(),
            avatar_url: "",
          },
          emailRedirectTo: `${window.location.origin}/auth/callback`,
        },
      });

      if (signUpError) {
        setError(signUpError.message);
      } else {
        // Auto-confirmed — redirect to account
        router.push("/account");
        router.refresh();
      }
    } catch {
      setError("An unexpected error occurred. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  if (checkingAuth) {
    return (
      <div className="min-h-screen bg-[#F8FAFC]">
        <Header />
        <div className="flex items-center justify-center py-24">
          <div className="w-6 h-6 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" />
        </div>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#F8FAFC]">
      <Header />

      {/* Breadcrumb */}
      <div className="bg-[#F8FAFC] border-b border-[#1e1e1e]">
        <div className="max-w-container mx-auto px-4 py-2.5">
          <nav aria-label="Breadcrumb" className="flex items-center gap-2 text-xs font-body text-[#555]">
            <Link href="/home-page" className="hover:text-[#1D4ED8] transition-colors">Home</Link>
            <span aria-hidden="true">/</span>
            <span className="text-[#888]">Create Account</span>
          </nav>
        </div>
      </div>

      <main className="max-w-container mx-auto px-4 py-12 md:py-16">
        <div className="max-w-md mx-auto">
          {/* Header */}
          <div className="text-center mb-8">
            <h1 className="font-heading text-2xl md:text-3xl font-bold text-[#0F172A] mb-2">
              Create Account
            </h1>
            <p className="font-body text-sm text-[#666]">
              Join AV Beat to save articles, track your reading history, and get personalized content.
            </p>
          </div>

          {/* Form Card */}
          <div className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-sm p-6 md:p-8">
            <form onSubmit={handleRegister} className="space-y-5" noValidate>
              {/* Error */}
              {error && (
                <div className="bg-[#1a0a0a] border border-[#1D4ED8] text-[#ff6b6b] font-body text-sm px-4 py-3 rounded-sm flex items-start gap-2">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="mt-0.5 flex-shrink-0" aria-hidden="true">
                    <circle cx="12" cy="12" r="10" /><line x1="15" y1="9" x2="9" y2="15" /><line x1="9" y1="9" x2="15" y2="15" />
                  </svg>
                  {error}
                </div>
              )}

              {/* Full Name */}
              <div>
                <label htmlFor="fullName" className="block font-body text-xs font-bold uppercase tracking-wider text-[#888] mb-1.5">
                  Full Name
                </label>
                <input
                  id="fullName"
                  type="text"
                  autoComplete="name"
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  placeholder="Jane Smith"
                  disabled={loading}
                  className="w-full h-10 px-3 bg-[#F8FAFC] border border-[#DCE6F2] text-[#e0e0e0] font-body text-sm rounded-sm placeholder-[#444] focus:outline-none focus:border-[#1D4ED8] focus-visible:ring-1 focus-visible:ring-[#1D4ED8] transition-colors disabled:opacity-50"
                />
              </div>

              {/* Email */}
              <div>
                <label htmlFor="email" className="block font-body text-xs font-bold uppercase tracking-wider text-[#888] mb-1.5">
                  Email Address
                </label>
                <input
                  id="email"
                  type="email"
                  autoComplete="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@example.com"
                  disabled={loading}
                  className="w-full h-10 px-3 bg-[#F8FAFC] border border-[#DCE6F2] text-[#e0e0e0] font-body text-sm rounded-sm placeholder-[#444] focus:outline-none focus:border-[#1D4ED8] focus-visible:ring-1 focus-visible:ring-[#1D4ED8] transition-colors disabled:opacity-50"
                />
              </div>

              {/* Password */}
              <div>
                <label htmlFor="password" className="block font-body text-xs font-bold uppercase tracking-wider text-[#888] mb-1.5">
                  Password
                </label>
                <input
                  id="password"
                  type="password"
                  autoComplete="new-password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Min. 6 characters"
                  disabled={loading}
                  className="w-full h-10 px-3 bg-[#F8FAFC] border border-[#DCE6F2] text-[#e0e0e0] font-body text-sm rounded-sm placeholder-[#444] focus:outline-none focus:border-[#1D4ED8] focus-visible:ring-1 focus-visible:ring-[#1D4ED8] transition-colors disabled:opacity-50"
                />
              </div>

              {/* Confirm Password */}
              <div>
                <label htmlFor="confirmPassword" className="block font-body text-xs font-bold uppercase tracking-wider text-[#888] mb-1.5">
                  Confirm Password
                </label>
                <input
                  id="confirmPassword"
                  type="password"
                  autoComplete="new-password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder="Re-enter password"
                  disabled={loading}
                  className="w-full h-10 px-3 bg-[#F8FAFC] border border-[#DCE6F2] text-[#e0e0e0] font-body text-sm rounded-sm placeholder-[#444] focus:outline-none focus:border-[#1D4ED8] focus-visible:ring-1 focus-visible:ring-[#1D4ED8] transition-colors disabled:opacity-50"
                />
              </div>

              {/* Submit */}
              <button
                type="submit"
                disabled={loading}
                className="w-full h-10 bg-[#1D4ED8] hover:bg-[#1E3A8A] text-white font-body text-sm font-bold uppercase tracking-wider rounded-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2">
                {loading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    Creating Account...
                  </>
                ) : (
                  "Create Account"
                )}
              </button>
            </form>

            {/* Divider */}
            <div className="flex items-center gap-3 my-6">
              <div className="flex-1 h-px bg-[#DCE6F2]" />
              <span className="font-body text-xs text-[#555]">Already have an account?</span>
              <div className="flex-1 h-px bg-[#DCE6F2]" />
            </div>

            {/* Login Link */}
            <Link
              href="/login"
              className="block w-full h-10 border border-[#DCE6F2] hover:border-[#1D4ED8] text-[#888] hover:text-[#1D4ED8] font-body text-sm font-bold uppercase tracking-wider rounded-sm transition-colors flex items-center justify-center">
              Sign In
            </Link>
          </div>
        </div>
      </main>

      <Footer />
    </div>
  );
}
