import React, { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Shield, Eye, EyeOff, Lock, Mail, User, Check, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { useToast } from '@/hooks/use-toast';

const AuthPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const { toast } = useToast();
  const [isSignup, setIsSignup] = useState(searchParams.get('signup') === 'true');
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const [formData, setFormData] = useState({
    email: '',
    username: '',
    password: '',
  });

  const [passwordStrength, setPasswordStrength] = useState({
    score: 0,
    label: '',
    checks: {
      length: false,
      uppercase: false,
      lowercase: false,
      number: false,
      special: false,
    },
  });

  useEffect(() => {
    const password = formData.password;
    const checks = {
      length: password.length >= 8,
      uppercase: /[A-Z]/.test(password),
      lowercase: /[a-z]/.test(password),
      number: /[0-9]/.test(password),
      special: /[!@#$%^&*(),.?":{}|<>]/.test(password),
    };

    const score = Object.values(checks).filter(Boolean).length;
    let label = '';
    if (score === 0) label = '';
    else if (score <= 2) label = 'Weak';
    else if (score <= 3) label = 'Fair';
    else if (score <= 4) label = 'Good';
    else label = 'Strong';

    setPasswordStrength({ score, label, checks });
  }, [formData.password]);

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

    // Simulate auth - in production, connect to Supabase
    await new Promise((resolve) => setTimeout(resolve, 1500));

    toast({
      title: isSignup ? 'Account Created!' : 'Welcome Back!',
      description: isSignup
        ? 'Your account has been created successfully.'
        : 'You have been logged in successfully.',
    });

    setIsLoading(false);
    navigate('/dashboard');
  };

  const getStrengthColor = () => {
    if (passwordStrength.score <= 2) return 'bg-destructive';
    if (passwordStrength.score <= 3) return 'bg-yellow-500';
    if (passwordStrength.score <= 4) return 'bg-accent';
    return 'bg-green-500';
  };

  return (
    <div className="min-h-screen flex items-center justify-center px-4 py-20 cyber-grid">
      {/* Background Effects */}
      <div className="fixed inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-primary/20 rounded-full blur-3xl animate-float" />
        <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-secondary/20 rounded-full blur-3xl animate-float" style={{ animationDelay: '1.5s' }} />
      </div>

      <div className="w-full max-w-md relative z-10">
        {/* Logo */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center gap-3 mb-4">
            <div className="relative">
              <Shield className="w-12 h-12 text-primary" />
              <div className="absolute inset-0 blur-xl bg-primary/50" />
            </div>
            <span className="font-display font-bold text-3xl text-gradient-primary">
              CipherX Labs
            </span>
          </div>
          <p className="text-muted-foreground">
            {isSignup ? 'Create your secure account' : 'Welcome back, agent'}
          </p>
        </div>

        {/* Auth Card */}
        <div className="glass-card p-8 neon-glow-purple">
          {/* Tabs */}
          <div className="flex mb-8 p-1 bg-muted/50 rounded-lg">
            <button
              onClick={() => setIsSignup(false)}
              className={cn(
                "flex-1 py-2 px-4 rounded-md font-display font-medium text-sm transition-all duration-300",
                !isSignup
                  ? "bg-cyber-gradient text-primary-foreground shadow-lg"
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              Login
            </button>
            <button
              onClick={() => setIsSignup(true)}
              className={cn(
                "flex-1 py-2 px-4 rounded-md font-display font-medium text-sm transition-all duration-300",
                isSignup
                  ? "bg-cyber-gradient text-primary-foreground shadow-lg"
                  : "text-muted-foreground hover:text-foreground"
              )}
            >
              Create Account
            </button>
          </div>

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Email */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-muted-foreground flex items-center gap-2">
                <Mail className="w-4 h-4" />
                Email
              </label>
              <Input
                type="email"
                placeholder="agent@cipherx.com"
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                required
              />
            </div>

            {/* Username (Signup only) */}
            {isSignup && (
              <div className="space-y-2 animate-fade-in-up">
                <label className="text-sm font-medium text-muted-foreground flex items-center gap-2">
                  <User className="w-4 h-4" />
                  Username
                </label>
                <Input
                  type="text"
                  placeholder="CyberAgent007"
                  value={formData.username}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  required
                />
              </div>
            )}

            {/* Password */}
            <div className="space-y-2">
              <label className="text-sm font-medium text-muted-foreground flex items-center gap-2">
                <Lock className="w-4 h-4" />
                Password
              </label>
              <div className="relative">
                <Input
                  type={showPassword ? 'text' : 'password'}
                  placeholder="••••••••••••"
                  value={formData.password}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  required
                  className="pr-12"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                >
                  {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              </div>

              {/* Password Strength Meter (Signup only) */}
              {isSignup && formData.password && (
                <div className="space-y-3 mt-4 animate-fade-in-up">
                  <div className="flex items-center justify-between">
                    <span className="text-xs text-muted-foreground">Password Strength</span>
                    <span className={cn(
                      "text-xs font-medium",
                      passwordStrength.score <= 2 && "text-destructive",
                      passwordStrength.score === 3 && "text-yellow-500",
                      passwordStrength.score >= 4 && "text-green-500"
                    )}>
                      {passwordStrength.label}
                    </span>
                  </div>
                  <div className="h-2 bg-muted rounded-full overflow-hidden">
                    <div
                      className={cn("h-full transition-all duration-500", getStrengthColor())}
                      style={{ width: `${(passwordStrength.score / 5) * 100}%` }}
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-2 text-xs">
                    {[
                      { key: 'length', label: '8+ characters' },
                      { key: 'uppercase', label: 'Uppercase' },
                      { key: 'lowercase', label: 'Lowercase' },
                      { key: 'number', label: 'Number' },
                      { key: 'special', label: 'Special char' },
                    ].map(({ key, label }) => (
                      <div
                        key={key}
                        className={cn(
                          "flex items-center gap-1",
                          passwordStrength.checks[key as keyof typeof passwordStrength.checks]
                            ? "text-green-500"
                            : "text-muted-foreground"
                        )}
                      >
                        {passwordStrength.checks[key as keyof typeof passwordStrength.checks] ? (
                          <Check className="w-3 h-3" />
                        ) : (
                          <X className="w-3 h-3" />
                        )}
                        {label}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Submit Button */}
            <Button
              type="submit"
              variant="neon"
              size="xl"
              className="w-full"
              disabled={isLoading}
            >
              {isLoading ? (
                <div className="flex items-center gap-2">
                  <div className="w-5 h-5 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" />
                  {isSignup ? 'Creating Account...' : 'Signing In...'}
                </div>
              ) : (
                <>{isSignup ? 'Create Account' : 'Sign In'}</>
              )}
            </Button>
          </form>

          {/* Divider */}
          <div className="relative my-6">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-border/50" />
            </div>
            <div className="relative flex justify-center">
              <span className="px-4 text-xs text-muted-foreground bg-card">
                Secure Authentication
              </span>
            </div>
          </div>

          {/* Info */}
          <p className="text-center text-xs text-muted-foreground">
            By continuing, you agree to our Terms of Service and Privacy Policy
          </p>
        </div>
      </div>
    </div>
  );
};

export default AuthPage;
