// src/app/(root)/register/RegisterForm.tsx
'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  Eye, EyeOff, Mail, Lock, User,
  AlertCircle, Loader2, ArrowRight, Check,
} from 'lucide-react';
import toast from 'react-hot-toast';

type FormData = {
  fullName: string;
  email: string;
  password: string;
  confirmPassword: string;
  agreeToTerms: boolean;
};
type Errors = Record<string, string>;

const passwordRequirements = (password: string) => [
  { text: 'At least 8 characters',  met: password.length >= 8 },
  { text: 'One lowercase letter',   met: /[a-z]/.test(password) },
  { text: 'One uppercase letter',   met: /[A-Z]/.test(password) },
  { text: 'One number',             met: /\d/.test(password) },
];

const passwordStrength = (password: string) => {
  if (!password) return null;
  if (password.length < 8) return 'Weak';
  if (/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) return 'Strong';
  return 'Medium';
};

const strengthConfig = {
  Weak:   { width: 'w-1/3', color: 'bg-red-500',    text: 'text-red-600' },
  Medium: { width: 'w-2/3', color: 'bg-yellow-500', text: 'text-yellow-600' },
  Strong: { width: 'w-full',color: 'bg-green-500',  text: 'text-green-600' },
};

export default function RegisterForm() {
  const router = useRouter();

  const [showPassword,        setShowPassword]        = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isLoading,           setIsLoading]           = useState(false);
  const [socialLoading,       setSocialLoading]       = useState(false);
  const [errors,              setErrors]              = useState<Errors>({});
  const [form,                setForm]                = useState<FormData>({
    fullName: '', email: '', password: '', confirmPassword: '', agreeToTerms: false,
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setForm(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value }));
    if (errors[name]) setErrors(prev => ({ ...prev, [name]: '' }));
  };

  const validate = (): boolean => {
    const e: Errors = {};
    if (!form.fullName.trim())                              e.fullName        = 'Full name is required';
    if (!form.email)                                        e.email           = 'Email is required';
    else if (!/\S+@\S+\.\S+/.test(form.email))             e.email           = 'Enter a valid email';
    if (!form.password)                                     e.password        = 'Password is required';
    else if (form.password.length < 8)                     e.password        = 'Minimum 8 characters';
    else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(form.password))
                                                            e.password        = 'Must include uppercase, lowercase & number';
    if (!form.confirmPassword)                              e.confirmPassword = 'Please confirm your password';
    else if (form.password !== form.confirmPassword)        e.confirmPassword = 'Passwords do not match';
    if (!form.agreeToTerms)                                 e.agreeToTerms    = 'You must agree to continue';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setIsLoading(true);
    try {
      const nameParts = form.fullName.trim().split(' ');
      const res = await fetch('/api/frontend/user/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email:      form.email,
          password:   form.password,
          first_name: nameParts[0],
          last_name:  nameParts.slice(1).join(' ') || '',
          phone:      '',
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || 'Registration failed');
      toast.success(data.message);
      router.push(data.token ? '/login' : '/login?registered=true');
    } catch (err) {
      setErrors({ submit: err instanceof Error ? err.message : 'Something went wrong.' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleGoogleSignup = async () => {
    setSocialLoading(true);
    try {
      const res  = await fetch('/api/frontend/user/auth/google/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ redirectUri: `${window.location.origin}/auth/callback` }),
      });
      const data = await res.json();
      if (data.redirectUrl) { window.location.href = data.redirectUrl; return; }
      throw new Error('No redirect URL received');
    } catch {
      toast.error('Failed to sign up with Google');
      setSocialLoading(false);
    }
  };

  const strength  = passwordStrength(form.password);
  const reqList   = passwordRequirements(form.password);
  const inputBase = 'w-full pl-10 pr-3 py-3 text-sm border rounded-xl bg-background text-text-primary placeholder-text-secondary/40 outline-none transition-all focus:ring-2 focus:ring-[#0066FF]/20';
  const inputCls  = (field: string) =>
    `${inputBase} ${errors[field] ? 'border-red-300 focus:border-red-400' : 'border-black/10 focus:border-[#0066FF]'}`;

  return (
    <div>
      {/* Header */}
      <div className="text-center mb-7">
        <div className="lg:hidden flex justify-center mb-5">
          <Link href="/">
            <div className="h-11 w-11 rounded-xl bg-linear-to-br from-[#0066FF] to-[#00D4FF] flex items-center justify-center">
              <span className="text-white font-bold text-lg">OE</span>
            </div>
          </Link>
        </div>
        <h2 className="text-2xl font-bold text-text-primary">Create your account</h2>
        <p className="mt-1.5 text-sm text-text-secondary">Join OutreachExpert and grow your SEO</p>
      </div>

      {/* Submit error */}
      {errors.submit && (
        <div className="mb-5 flex items-start gap-3 p-3.5 rounded-xl bg-red-50 border border-red-200">
          <AlertCircle className="h-4 w-4 text-red-500 shrink-0 mt-0.5" />
          <p className="text-sm text-red-700">{errors.submit}</p>
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">

        {/* Full Name */}
        <div>
          <label className="block text-xs font-medium text-text-primary mb-1.5">Full Name</label>
          <div className="relative">
            <User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
            <input
              type="text"
              name="fullName"
              value={form.fullName}
              onChange={handleChange}
              placeholder="John Doe"
              autoComplete="name"
              className={inputCls('fullName')}
            />
          </div>
          {errors.fullName && (
            <p className="mt-1.5 text-xs text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />{errors.fullName}
            </p>
          )}
        </div>

        {/* Email */}
        <div>
          <label className="block text-xs font-medium text-text-primary mb-1.5">Email</label>
          <div className="relative">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
            <input
              type="email"
              name="email"
              value={form.email}
              onChange={handleChange}
              placeholder="you@company.com"
              autoComplete="email"
              className={inputCls('email')}
            />
          </div>
          {errors.email && (
            <p className="mt-1.5 text-xs text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />{errors.email}
            </p>
          )}
        </div>

        {/* Password */}
        <div>
          <label className="block text-xs font-medium text-text-primary mb-1.5">Password</label>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
            <input
              type={showPassword ? 'text' : 'password'}
              name="password"
              value={form.password}
              onChange={handleChange}
              placeholder="••••••••"
              autoComplete="new-password"
              className={`${inputCls('password')} pr-10`}
            />
            <button
              type="button"
              onClick={() => setShowPassword(p => !p)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-text-secondary hover:text-text-primary transition-colors"
            >
              {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>

          {/* Strength bar */}
          {strength && (
            <div className="mt-2">
              <div className="flex items-center justify-between mb-1">
                <span className="text-xs text-text-secondary">Strength</span>
                <span className={`text-xs font-medium ${strengthConfig[strength].text}`}>{strength}</span>
              </div>
              <div className="w-full bg-black/8 rounded-full h-1.5">
                <div className={`h-1.5 rounded-full transition-all duration-300 ${strengthConfig[strength].width} ${strengthConfig[strength].color}`} />
              </div>
            </div>
          )}

          {errors.password && (
            <p className="mt-1.5 text-xs text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />{errors.password}
            </p>
          )}
        </div>

        {/* Confirm Password */}
        <div>
          <label className="block text-xs font-medium text-text-primary mb-1.5">Confirm Password</label>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-text-secondary" />
            <input
              type={showConfirmPassword ? 'text' : 'password'}
              name="confirmPassword"
              value={form.confirmPassword}
              onChange={handleChange}
              placeholder="••••••••"
              autoComplete="new-password"
              className={`${inputCls('confirmPassword')} pr-10`}
            />
            <button
              type="button"
              onClick={() => setShowConfirmPassword(p => !p)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-text-secondary hover:text-text-primary transition-colors"
            >
              {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
          {errors.confirmPassword && (
            <p className="mt-1.5 text-xs text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />{errors.confirmPassword}
            </p>
          )}
        </div>

        {/* Password requirements */}
        {form.password && (
          <div className="p-3 bg-black/2 rounded-xl border border-black/8">
            <div className="grid grid-cols-2 gap-1.5">
              {reqList.map(({ text, met }) => (
                <div key={text} className="flex items-center gap-1.5">
                  <div className={`flex h-4 w-4 shrink-0 items-center justify-center rounded-full ${met ? 'bg-green-100 text-green-600' : 'bg-black/5 text-text-secondary/40'}`}>
                    <Check className="h-2.5 w-2.5" />
                  </div>
                  <span className={`text-xs ${met ? 'text-green-600' : 'text-text-secondary'}`}>{text}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Terms */}
        <div>
          <label className="flex items-start gap-2.5 cursor-pointer">
            <input
              type="checkbox"
              name="agreeToTerms"
              checked={form.agreeToTerms}
              onChange={handleChange}
              className="mt-0.5 w-4 h-4 rounded border-black/20 text-[#0066FF] focus:ring-[#0066FF]/20 shrink-0"
            />
            <span className="text-xs text-text-secondary leading-relaxed">
              I agree to the{' '}
              <Link href="/terms" className="text-[#0066FF] hover:text-[#0052cc] transition-colors">Terms of Service</Link>
              {' '}and{' '}
              <Link href="/privacy" className="text-[#0066FF] hover:text-[#0052cc] transition-colors">Privacy Policy</Link>
            </span>
          </label>
          {errors.agreeToTerms && (
            <p className="mt-1.5 text-xs text-red-500 flex items-center gap-1">
              <AlertCircle className="h-3 w-3" />{errors.agreeToTerms}
            </p>
          )}
        </div>

        {/* Submit */}
        <button
          type="submit"
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 py-3 px-4 rounded-xl
            bg-[#0066FF] hover:bg-[#0052cc] active:scale-[0.99] text-white text-sm font-semibold
            transition-all disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {isLoading
            ? <><Loader2 className="h-4 w-4 animate-spin" /> Creating account...</>
            : <>Create account <ArrowRight className="h-4 w-4" /></>
          }
        </button>

      </form>

      {/* Below form */}
      <div className="mt-6 space-y-4">

        {/* Divider */}
        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-black/8" />
          </div>
          <div className="relative flex justify-center">
            <span className="px-3 bg-surface text-xs text-text-secondary">or continue with</span>
          </div>
        </div>

        {/* Google */}
        <button
          onClick={handleGoogleSignup}
          disabled={socialLoading}
          className="w-full flex items-center justify-center gap-3 py-3 px-4 rounded-xl
            border border-black/10 hover:bg-black/3 active:scale-[0.99]
            text-sm text-text-primary transition-all
            disabled:opacity-60 disabled:cursor-not-allowed"
        >
          {socialLoading ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <svg className="h-4 w-4 shrink-0" viewBox="0 0 24 24">
              <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
              <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
              <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"/>
              <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
            </svg>
          )}
          Continue with Google
        </button>

        {/* Sign in link */}
        <p className="pt-2 border-t border-black/8 text-center text-xs text-text-secondary">
          Already have an account?{' '}
          <Link href="/login" className="font-medium text-[#0066FF] hover:text-[#0052cc] transition-colors">
            Sign in here
          </Link>
        </p>

      </div>
    </div>
  );
}