'use client';

import React, { useState, Suspense } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { 
  Mail, 
  Lock, 
  Eye, 
  EyeOff, 
  Building, 
  Phone
} from 'lucide-react';

function RegisterPageContent() {
  const [businessName, setBusinessName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const { register } = useAuth();

  const searchParams = useSearchParams();
  const plan = searchParams.get('plan');
  const cycle = searchParams.get('cycle');

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

    try {
      const redirectTo = plan ? `/dashboard/billing?plan=${plan}&cycle=${cycle || 'annual'}` : undefined;
      await register(businessName, email, password, phone || undefined, redirectTo);
    } catch (err: any) {
      setError(err.message || 'Registration failed. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen w-full bg-[var(--outer-bg)] text-slate-800 flex flex-col lg:flex-row relative overflow-hidden">
      
      {/* Left Panel - Form Container */}
      <div className="w-full lg:w-1/2 flex flex-col justify-center px-6 py-16 sm:px-12 lg:px-20 xl:px-28 z-10 bg-[var(--bg-color)]">
        <div className="w-full max-w-md mx-auto">
          
          {/* Logo & Header */}
          <div className="mb-6 flex flex-col items-start">
            <span className="font-black text-xl tracking-wide text-emerald-600 font-sans mb-6 select-none">
              WhatsApp Commerce Hub
            </span>
            
            <h1 className="text-3xl font-extrabold text-[#EFEAE2] dark:text-[#EFEAE2] tracking-tight font-sans">
              Register Business
            </h1>
            <p className="text-sm text-slate-400 dark:text-[#EFEAE2]/80 mt-2">
              Launch your WhatsApp storefront in minutes
            </p>
          </div>

          {/* Error Message */}
          {error && (
            <div className="bg-red-50 border border-red-200 text-red-600 text-xs rounded-xl p-4 mb-6 flex items-start gap-3">
              <div className="h-1.5 w-1.5 rounded-full bg-red-500 mt-1.5 flex-shrink-0" />
              <p>{error}</p>
            </div>
          )}

          {/* Registration Form */}
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-[11px] font-bold uppercase tracking-wider text-slate-400 mb-2">
                Business Name
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
                  <Building className="h-4 w-4" />
                </div>
                <input
                  type="text"
                  value={businessName}
                  onChange={(e) => setBusinessName(e.target.value)}
                  required
                  className="w-full bg-white border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 font-sans shadow-sm"
                  placeholder="Acme Corporation"
                />
              </div>
            </div>

            <div>
              <label className="block text-[11px] font-bold uppercase tracking-wider text-slate-400 mb-2">
                Email Address
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
                  <Mail className="h-4 w-4" />
                </div>
                <input
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  className="w-full bg-white border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 font-sans shadow-sm"
                  placeholder="contact@company.com"
                />
              </div>
            </div>

            <div>
              <label className="block text-[11px] font-bold uppercase tracking-wider text-slate-400 mb-2">
                WhatsApp Phone Number
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
                  <Phone className="h-4 w-4" />
                </div>
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  required
                  className="w-full bg-white border border-slate-200 rounded-xl pl-11 pr-4 py-3 text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 font-sans shadow-sm"
                  placeholder="263771234567"
                />
              </div>
            </div>

            <div>
              <label className="block text-[11px] font-bold uppercase tracking-wider text-slate-400 mb-2">
                Password
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-slate-400">
                  <Lock className="h-4 w-4" />
                </div>
                <input
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  minLength={6}
                  className="w-full bg-white border border-slate-200 rounded-xl pl-11 pr-11 py-3 text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:border-emerald-500 focus:ring-1 focus:ring-emerald-500 font-sans shadow-sm"
                  placeholder="•••••••• (min 6 characters)"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute inset-y-0 right-0 pr-3.5 flex items-center text-slate-400 hover:text-slate-600 transition-colors cursor-pointer"
                >
                  {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>

            {/* Terms Agreement (visual styling) */}
            <div className="pt-1 select-none">
              <p className="text-[11px] text-slate-500 leading-normal">
                By creating an account, you agree to our{' '}
                <a href="#" onClick={(e) => e.preventDefault()} className="text-emerald-600 hover:underline">Terms of Service</a>
                {' '}and{' '}
                <a href="#" onClick={(e) => e.preventDefault()} className="text-emerald-600 hover:underline">Privacy Policy</a>.
              </p>
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={submitting}
              className="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3.5 rounded-xl text-sm transition-all shadow-sm active:scale-[0.98] disabled:opacity-50 disabled:pointer-events-none cursor-pointer flex items-center justify-center gap-2 mt-4"
            >
              {submitting ? (
                <>
                  <div className="h-4 w-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                  <span>Registering...</span>
                </>
              ) : (
                <span>Register Business</span>
              )}
            </button>
          </form>

          {/* Footer Navigation */}
          <div className="mt-8 text-center text-xs text-slate-500">
            Already have an account?{' '}
            <Link href={plan ? `/login?plan=${plan}&cycle=${cycle || 'annual'}` : '/login'} className="text-emerald-600 hover:text-emerald-700 hover:underline font-semibold transition-colors">
              Sign In
            </Link>
          </div>

        </div>
      </div>

      {/* Right Panel - Responsive Typography Showcase (Dark Green Theme) */}
      <div className="w-full lg:w-1/2 bg-[#06402B] relative flex flex-col items-center justify-center p-8 sm:p-12 lg:p-20 overflow-hidden border-t lg:border-t-0 lg:border-l border-white/5 min-h-[280px] lg:min-h-0 dark-section text-[#EFEAE2]" style={{ color: '#EFEAE2' }}>
        
        {/* Subtle background glow */}
        <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(16,185,129,0.1)_0%,transparent_60%)]"></div>

        <div className="max-w-md w-full flex flex-col items-center justify-center text-center z-10 space-y-6">
          
          {/* Static Branding Display */}
          <div className="py-6 select-none">
            <h1 className="text-4xl sm:text-5xl font-black tracking-widest !text-[#EFEAE2] text-glow Outfit" style={{ color: '#EFEAE2' }}>
              WHATSAPP COMMERCE HUB
            </h1>
          </div>

          {/* Marketing Texts */}
          <div className="space-y-4">
            <h2 className="text-2xl font-extrabold !text-[#EFEAE2] tracking-tight Outfit" style={{ color: '#EFEAE2' }}>
              Launch your chat shop in minutes.
            </h2>
            <p className="text-sm !text-[#EFEAE2]/80 max-w-sm mx-auto leading-relaxed" style={{ color: 'rgba(239, 234, 226, 0.85)' }}>
              Everything you need to manage products, categories, templates, and sessions in a single control panel.
            </p>
          </div>

        </div>

      </div>

    </div>
  );
}

export default function RegisterPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center bg-[var(--outer-bg)] text-white">Loading RegisterPage...</div>}>
      <RegisterPageContent />
    </Suspense>
  );
}
