'use client';

import { useState, useCallback } from 'react';
import { motion } from 'framer-motion';
import { Shield, Eye, EyeOff, Loader2, AlertCircle, Check, UserPlus, ChevronDown, ChevronUp } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { useAppStore } from '@/store/app-store';
import { useLangStore } from '@/store/lang-store';
import { toast } from 'sonner';
import type { UserType } from '@/types';

// ─── Password Requirements ────────────────────────────────────────────────────

interface PasswordCheckProps {
  password: string;
}

function PasswordChecks({ password }: PasswordCheckProps) {
  const checks = [
    { label: 'At least 6 characters', met: password.length >= 6 },
    { label: 'Contains a number', met: /\d/.test(password) },
    { label: 'Contains uppercase letter', met: /[A-Z]/.test(password) },
  ];

  return (
    <div className="space-y-1.5 mt-2">
      {checks.map((check) => (
        <div key={check.label} className="flex items-center gap-2 text-xs">
          <div
            className={`h-3.5 w-3.5 rounded-full flex items-center justify-center transition-colors ${
              check.met
                ? 'bg-emerald-500/20 text-emerald-500'
                : 'bg-muted text-muted-foreground'
            }`}
          >
            <Check className="h-2.5 w-2.5" />
          </div>
          <span className={check.met ? 'text-emerald-600 dark:text-emerald-400' : 'text-muted-foreground'}>
            {check.label}
          </span>
        </div>
      ))}
    </div>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export function RegisterPage() {
  const navigate = useAppStore((s) => s.navigate);
  const setUser = useAppStore((s) => s.setUser);
  const t = useLangStore((s) => s.t);

  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [agreeTerms, setAgreeTerms] = useState(false);

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

      // Validation
      if (!name.trim()) {
        setError('Name is required');
        return;
      }

      if (!email.trim()) {
        setError('Email is required');
        return;
      }

      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) {
        setError('Please enter a valid 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;
      }

      setIsLoading(true);

      try {
        const res = await fetch('/api/auth/register', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            email: email.trim(),
            name: name.trim(),
            password,
          }),
        });

        const data = await res.json();

        if (data.success) {
          const userData: UserType = data.data;
          localStorage.setItem('scamchecker_user', JSON.stringify(userData));
          setUser(userData);
          toast.success('Account created successfully! Welcome to ScamChecker BD.');
          navigate('dashboard');
        } else {
          setError(data.error || 'Registration failed');
          toast.error(data.error || 'Registration failed');
        }
      } catch {
        setError('Something went wrong. Please try again.');
        toast.error('Something went wrong. Please try again.');
      } finally {
        setIsLoading(false);
      }
    },
    [name, email, password, confirmPassword, setUser, navigate]
  );

  return (
    <div className="min-h-[80vh] flex flex-col lg:flex-row">
      {/* ─── Left Side - Branding / Illustration ──────────────────────────── */}
      <div className="relative hidden lg:flex lg:w-1/2 items-center justify-center overflow-hidden bg-gradient-to-br from-teal-900 via-emerald-800 to-emerald-900">
        {/* Animated pattern background */}
        <div className="absolute inset-0 cyber-grid opacity-30" />
        
        {/* Floating decorative elements - CSS only */}
        <div className="absolute top-1/3 right-1/4 w-[350px] h-[350px] rounded-full opacity-20 animate-pulse-slow"
          style={{ background: 'radial-gradient(circle, oklch(0.6 0.118 184.704 / 0.4), transparent 70%)' }} />
        <div className="absolute bottom-1/3 left-1/4 w-[250px] h-[250px] rounded-full opacity-15 animate-pulse-slow"
          style={{ background: 'radial-gradient(circle, oklch(0.558 0.158 155 / 0.4), transparent 70%)', animationDelay: '2s' }} />
        
        {/* Small floating dots - CSS only */}
        <div className="absolute top-[20%] right-[15%] w-2.5 h-2.5 rounded-full bg-teal-400/25 animate-float" />
        <div className="absolute top-[50%] left-[20%] w-2 h-2 rounded-full bg-emerald-400/20 animate-float" style={{ animationDelay: '3s' }} />
        <div className="absolute bottom-[25%] right-[30%] w-1.5 h-1.5 rounded-full bg-teal-300/20 animate-float" style={{ animationDelay: '1.5s' }} />
        <div className="absolute top-[40%] right-[40%] w-2 h-2 rounded-full bg-emerald-300/20 animate-float" style={{ animationDelay: '4s' }} />
        <div className="absolute bottom-[15%] left-[15%] w-3 h-3 rounded-full bg-teal-400/15 animate-float" style={{ animationDelay: '2.5s' }} />

        {/* Content */}
        <div className="relative z-10 text-center px-12 max-w-lg">
          <motion.div
            initial={{ opacity: 0, scale: 0.8 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.6, ease: 'easeOut' }}
          >
            {/* Shield Logo */}
            <div className="shield-glow inline-flex p-6 rounded-3xl bg-teal-500/15 border border-teal-400/20 mb-8">
              <UserPlus className="h-16 w-16 text-teal-300" strokeWidth={1.5} />
            </div>
            
            <h1 className="text-4xl font-extrabold text-white mb-4 leading-tight">
              Join the Fight<br />
              <span className="bg-gradient-to-r from-teal-300 to-emerald-300 bg-clip-text text-transparent">
                Against Scams
              </span>
            </h1>
            
            <p className="text-teal-200/70 text-lg leading-relaxed mb-8">
              Create an account to report scammers, save suspicious entities, and help protect the Bangladesh community.
            </p>

            {/* Features list */}
            <div className="space-y-3 text-left max-w-xs mx-auto">
              {[
                'Report and track scams in real-time',
                'Save suspicious numbers for quick lookup',
                'Get AI-powered scam detection',
              ].map((feature, i) => (
                <div key={i} className="flex items-center gap-2">
                  <div className="flex-shrink-0 w-5 h-5 rounded-full bg-emerald-500/20 flex items-center justify-center">
                    <Check className="h-3 w-3 text-emerald-300" />
                  </div>
                  <span className="text-sm text-teal-200/80">{feature}</span>
                </div>
              ))}
            </div>

            {/* Social proof */}
            <div className="mt-8 flex items-center justify-center gap-3">
              <div className="flex -space-x-2">
                {['A', 'N', 'K', 'R'].map((initial, i) => (
                  <div
                    key={i}
                    className="w-7 h-7 rounded-full border-2 border-teal-900 flex items-center justify-center text-[10px] font-bold text-white"
                    style={{
                      backgroundColor: [
                        'oklch(0.6 0.118 184.704)',
                        'oklch(0.558 0.158 155)',
                        'oklch(0.6 0.118 184.704)',
                        'oklch(0.558 0.158 155)',
                      ][i],
                    }}
                  >
                    {initial}
                  </div>
                ))}
              </div>
              <span className="text-xs text-teal-200/60">
                <span className="font-semibold text-teal-200/90">10,000+</span> members already
              </span>
            </div>
          </motion.div>
        </div>
      </div>

      {/* ─── Right Side - Form ──────────────────────────────────────────── */}
      <div className="flex-1 flex items-center justify-center px-4 py-12 sm:px-8 lg:px-16">
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, ease: 'easeOut' }}
          className="w-full max-w-md"
        >
          {/* Mobile-only shield logo */}
          <div className="flex justify-center mb-6 lg:hidden">
            <div className="shield-glow p-3 rounded-2xl bg-emerald-500/10 border border-emerald-500/20">
              <UserPlus className="h-10 w-10 text-emerald-500" />
            </div>
          </div>

          <div className="text-center mb-8">
            <h2 className="text-2xl sm:text-3xl font-bold">{t('auth.createAccount')}</h2>
            <p className="mt-2 text-muted-foreground">
              {t('auth.joinCommunity')}
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Error Message */}
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex items-center gap-2 p-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm"
              >
                <AlertCircle className="h-4 w-4 shrink-0" />
                {error}
              </motion.div>
            )}

            {/* Name */}
            <div className="space-y-2">
              <Label htmlFor="register-name">{t('auth.name')}</Label>
              <Input
                id="register-name"
                type="text"
                placeholder="Your full name"
                value={name}
                onChange={(e) => {
                  setName(e.target.value);
                  if (error) setError('');
                }}
                disabled={isLoading}
                autoComplete="name"
                className="h-11 focus-visible:ring-emerald-500/30 focus-visible:border-emerald-500/50"
              />
            </div>

            {/* Email */}
            <div className="space-y-2">
              <Label htmlFor="register-email">{t('auth.email')}</Label>
              <Input
                id="register-email"
                type="email"
                placeholder="you@example.com"
                value={email}
                onChange={(e) => {
                  setEmail(e.target.value);
                  if (error) setError('');
                }}
                disabled={isLoading}
                autoComplete="email"
                className="h-11 focus-visible:ring-emerald-500/30 focus-visible:border-emerald-500/50"
              />
            </div>

            {/* Password */}
            <div className="space-y-2">
              <Label htmlFor="register-password">{t('auth.password')}</Label>
              <div className="relative">
                <Input
                  id="register-password"
                  type={showPassword ? 'text' : 'password'}
                  placeholder="Min 6 characters"
                  value={password}
                  onChange={(e) => {
                    setPassword(e.target.value);
                    if (error) setError('');
                  }}
                  disabled={isLoading}
                  autoComplete="new-password"
                  className="h-11 pr-10 focus-visible:ring-emerald-500/30 focus-visible:border-emerald-500/50"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                  tabIndex={-1}
                >
                  {showPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>
              {password.length > 0 && <PasswordChecks password={password} />}
            </div>

            {/* Confirm Password */}
            <div className="space-y-2">
              <Label htmlFor="register-confirm-password">{t('auth.confirmPassword')}</Label>
              <div className="relative">
                <Input
                  id="register-confirm-password"
                  type={showConfirmPassword ? 'text' : 'password'}
                  placeholder="Re-enter your password"
                  value={confirmPassword}
                  onChange={(e) => {
                    setConfirmPassword(e.target.value);
                    if (error) setError('');
                  }}
                  disabled={isLoading}
                  autoComplete="new-password"
                  className={`h-11 pr-10 focus-visible:ring-emerald-500/30 ${
                    confirmPassword.length > 0 && password !== confirmPassword
                      ? 'border-destructive focus-visible:border-destructive'
                      : confirmPassword.length > 0 && password === confirmPassword
                        ? 'border-emerald-500 focus-visible:border-emerald-500'
                        : 'focus-visible:border-emerald-500/50'
                  }`}
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                  tabIndex={-1}
                >
                  {showConfirmPassword ? (
                    <EyeOff className="h-4 w-4" />
                  ) : (
                    <Eye className="h-4 w-4" />
                  )}
                </button>
              </div>
              {confirmPassword.length > 0 && password !== confirmPassword && (
                <p className="text-xs text-destructive">Passwords do not match</p>
              )}
              {confirmPassword.length > 0 && password === confirmPassword && (
                <p className="text-xs text-emerald-500">Passwords match</p>
              )}
            </div>

            {/* Terms agreement */}
            <div className="flex items-start gap-2 pt-1">
              <Checkbox
                id="agree-terms"
                checked={agreeTerms}
                onCheckedChange={(checked) => setAgreeTerms(checked === true)}
                className="mt-0.5 data-[state=checked]:bg-emerald-500 data-[state=checked]:border-emerald-500"
              />
              <Label htmlFor="agree-terms" className="text-xs text-muted-foreground cursor-pointer leading-relaxed">
                I agree to the{' '}
                <span className="text-emerald-600 dark:text-emerald-400 font-medium">Terms of Service</span>
                {' '}and{' '}
                <span className="text-emerald-600 dark:text-emerald-400 font-medium">Privacy Policy</span>
              </Label>
            </div>

            {/* Submit Button */}
            <Button
              type="submit"
              disabled={isLoading}
              className="w-full h-11 text-base rounded-xl bg-gradient-to-r from-emerald-600 to-teal-500 hover:from-emerald-700 hover:to-teal-600 dark:from-emerald-500 dark:to-teal-400 dark:hover:from-emerald-600 dark:hover:to-teal-500 shadow-lg shadow-emerald-500/20 transition-all duration-200"
            >
              {isLoading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Creating Account...
                </>
              ) : (
                <>
                  <UserPlus className="h-4 w-4" />
                  {t('auth.registerButton')}
                </>
              )}
            </Button>
          </form>

          {/* Register Link */}
          <p className="mt-6 text-sm text-muted-foreground text-center">
            {t('auth.hasAccount')}{' '}
            <button
              type="button"
              onClick={() => navigate('login')}
              className="font-semibold text-emerald-600 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-300 transition-colors"
            >
              {t('auth.loginButton')}
            </button>
          </p>
        </motion.div>
      </div>
    </div>
  );
}
