import { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Separator } from '@/components/ui/separator';
import { Zap, Mail, Lock, User, Eye, EyeOff } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { handleError } from '@/lib/errorHandler';
import { TurnstileCaptcha } from './TurnstileCaptcha';
import { notificationService } from '@/lib/notificationService';
import { useCaptchaBypass } from '@/hooks/useCaptchaBypass';
import { MFAChallenge } from './MFAChallenge';
import { verifyMfaUpgrade } from '@/lib/authService';
import { setAuthMethod } from '@/lib/sessionFlags';
import { validateEmailNotDisposable } from '@/lib/emailValidation';
import { getErrorMessage } from '@/lib/errorHandler';
import { logger } from '@/lib/logger';
import type { SignInOptions } from '@/types/supabase-auth';

interface AuthModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  defaultTab?: 'signin' | 'signup';
}

export function AuthModal({ open, onOpenChange, defaultTab = 'signin' }: AuthModalProps) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [magicLinkLoading, setMagicLinkLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [captchaToken, setCaptchaToken] = useState<string | null>(null);
  const [captchaKey, setCaptchaKey] = useState(0);
  const [signInCaptchaToken, setSignInCaptchaToken] = useState<string | null>(null);
  const [signInCaptchaKey, setSignInCaptchaKey] = useState(0);
  const [mfaFactorId, setMfaFactorId] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    confirmPassword: '',
    username: '',
    displayName: ''
  });

  const { requireCaptcha } = useCaptchaBypass();

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData(prev => ({
      ...prev,
      [e.target.name]: e.target.value
    }));
  };

  const handleSignIn = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    if (requireCaptcha && !signInCaptchaToken) {
      toast({
        variant: "destructive",
        title: "CAPTCHA required",
        description: "Please complete the CAPTCHA verification."
      });
      setLoading(false);
      return;
    }

    const tokenToUse = signInCaptchaToken;
    setSignInCaptchaToken(null);

    try {
      const signInOptions: SignInOptions = {
        email: formData.email,
        password: formData.password,
      };
      
      if (tokenToUse) {
        signInOptions.options = { captchaToken: tokenToUse };
      }

      const { data, error } = await supabase.auth.signInWithPassword(signInOptions);
      if (error) throw error;

      // CRITICAL: Check ban status immediately after successful authentication
      const { data: profile } = await supabase
        .from('profiles')
        .select('banned, ban_reason')
        .eq('user_id', data.user.id)
        .single();
      
      if (profile?.banned) {
        // Sign out immediately
        await supabase.auth.signOut();
        
        const reason = profile.ban_reason 
          ? `Reason: ${profile.ban_reason}`
          : 'Contact support for assistance.';
        
        toast({
          variant: "destructive",
          title: "Account Suspended",
          description: `Your account has been suspended. ${reason}`,
          duration: 10000
        });
        setLoading(false);
        return; // Stop authentication flow
      }

      // Check if MFA is required (user exists but no session)
      if (data.user && !data.session) {
        const totpFactor = data.user.factors?.find(f => f.factor_type === 'totp' && f.status === 'verified');
        
        if (totpFactor) {
          setMfaFactorId(totpFactor.id);
          setLoading(false);
          return;
        }
      }
      
      // Track auth method for audit logging
      setAuthMethod('password');

      // Check if MFA step-up is required
      const { handlePostAuthFlow } = await import('@/lib/authService');
      const postAuthResult = await handlePostAuthFlow(data.session, 'password');

      if (postAuthResult.success && postAuthResult.data?.shouldRedirect) {
        // Get the TOTP factor ID
        const { data: factors } = await supabase.auth.mfa.listFactors();
        const totpFactor = factors?.totp?.find(f => f.status === 'verified');
        
        if (totpFactor) {
          setMfaFactorId(totpFactor.id);
          setLoading(false);
          return; // Stay in modal, show MFA challenge
        }
      }
      
      toast({
        title: "Welcome back!",
        description: "You've been signed in successfully."
      });
      
      // Wait for auth state to propagate before closing
      await new Promise(resolve => setTimeout(resolve, 100));
      
      onOpenChange(false);
    } catch (error: unknown) {
      setSignInCaptchaKey(prev => prev + 1);
      handleError(error, {
        action: 'Sign In',
        metadata: { 
          method: 'password',
          hasCaptcha: !!tokenToUse
          // ⚠️ NEVER log: email, password, tokens
        }
      });
    } finally {
      setLoading(false);
    }
  };

  const handleMfaSuccess = async () => {
    // Verify AAL upgrade was successful
    const { data: { session } } = await supabase.auth.getSession();
    const verification = await verifyMfaUpgrade(session);
    
    if (!verification.success) {
      toast({
        variant: "destructive",
        title: "MFA Verification Failed",
        description: verification.error || "Failed to upgrade session. Please try again."
      });
      
      // Force sign out on verification failure
      await supabase.auth.signOut();
      setMfaFactorId(null);
      return;
    }
    
    setMfaFactorId(null);
    onOpenChange(false);
  };

  const handleMfaCancel = () => {
    setMfaFactorId(null);
    setSignInCaptchaKey(prev => prev + 1);
  };

  const handleSignUp = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    if (formData.password !== formData.confirmPassword) {
      toast({
        variant: "destructive",
        title: "Passwords don't match",
        description: "Please make sure your passwords match."
      });
      setLoading(false);
      return;
    }

    if (formData.password.length < 6) {
      toast({
        variant: "destructive",
        title: "Password too short",
        description: "Password must be at least 6 characters long."
      });
      setLoading(false);
      return;
    }

    if (requireCaptcha && !captchaToken) {
      toast({
        variant: "destructive",
        title: "CAPTCHA required",
        description: "Please complete the CAPTCHA verification."
      });
      setLoading(false);
      return;
    }

    const tokenToUse = captchaToken;
    setCaptchaToken(null);

    try {
      // Validate email is not disposable
      const emailValidation = await validateEmailNotDisposable(formData.email);

      if (!emailValidation.valid) {
        toast({
          variant: "destructive",
          title: "Invalid Email",
          description: emailValidation.reason || "Please use a permanent email address"
        });
        setCaptchaKey(prev => prev + 1);
        setLoading(false);
        return;
      }

      const signUpOptions: any = {
        email: formData.email,
        password: formData.password,
        options: {
          data: {
            username: formData.username,
            display_name: formData.displayName
          }
        }
      };

      if (tokenToUse) {
        signUpOptions.options.captchaToken = tokenToUse;
      }

      const { data, error } = await supabase.auth.signUp(signUpOptions);
      
      if (error) throw error;

      if (data.user) {
        notificationService.createSubscriber({
          subscriberId: data.user.id,
          email: formData.email,
          firstName: formData.username,
          data: {
            username: formData.username,
          }
        }).catch(err => {
          logger.error('Failed to register Novu subscriber', { error: getErrorMessage(err) });
        });
      }
      
      toast({
        title: "Welcome to ThrillWiki!",
        description: "Please check your email to verify your account."
      });
      onOpenChange(false);
    } catch (error: unknown) {
      setCaptchaKey(prev => prev + 1);
      handleError(error, {
        action: 'Sign Up',
        metadata: { 
          hasCaptcha: !!tokenToUse,
          hasUsername: !!formData.username
          // ⚠️ NEVER log: email, password, username
        }
      });
    } finally {
      setLoading(false);
    }
  };

  const handleMagicLinkSignIn = async (email: string) => {
    if (!email) {
      toast({
        variant: "destructive",
        title: "Email required",
        description: "Please enter your email address to receive a magic link."
      });
      return;
    }

    setMagicLinkLoading(true);
    
    try {
      const { error } = await supabase.auth.signInWithOtp({
        email,
        options: {
          emailRedirectTo: `${window.location.origin}/auth/callback`
        }
      });
      
      if (error) throw error;
      
      toast({
        title: "Magic link sent!",
        description: "Check your email for a sign-in link."
      });
      onOpenChange(false);
    } catch (error: unknown) {
      handleError(error, {
        action: 'Send Magic Link',
        metadata: { 
          method: 'magic_link'
          // ⚠️ NEVER log: email, link
        }
      });
    } finally {
      setMagicLinkLoading(false);
    }
  };

  const handleSocialSignIn = async (provider: 'google' | 'discord') => {
    try {
      const { error } = await supabase.auth.signInWithOAuth({
        provider,
        options: {
          redirectTo: `${window.location.origin}/auth/callback`,
          // Request additional scopes for avatar access
          scopes: provider === 'google' 
            ? 'email profile'
            : 'identify email'
        }
      });
      if (error) throw error;
    } catch (error: unknown) {
      handleError(error, {
        action: 'Social Sign In',
        metadata: { 
          provider,
          method: 'oauth'
        }
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[440px]">
        <DialogHeader>
          <DialogTitle className="text-center text-2xl bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
            ThrillWiki
          </DialogTitle>
          <DialogDescription className="text-center">
            Join the ultimate theme park community
          </DialogDescription>
        </DialogHeader>

        <Tabs defaultValue={defaultTab} className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="signin">Sign In</TabsTrigger>
            <TabsTrigger value="signup">Sign Up</TabsTrigger>
          </TabsList>

          <TabsContent value="signin" className="space-y-4 mt-4">
            {mfaFactorId ? (
              <MFAChallenge
                factorId={mfaFactorId}
                onSuccess={handleMfaSuccess}
                onCancel={handleMfaCancel}
              />
            ) : (
              <>
                <form onSubmit={handleSignIn} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="modal-signin-email">Email</Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
                  <Input
                    id="modal-signin-email"
                    name="email"
                    type="email"
                    placeholder="your@email.com"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="pl-10"
                    autoComplete="email"
                    required
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="modal-signin-password">Password</Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
                  <Input
                    id="modal-signin-password"
                    name="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="Your password"
                    value={formData.password}
                    onChange={handleInputChange}
                    className="pl-10 pr-10"
                    autoComplete="current-password"
                    required
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-0 top-0 h-full px-3"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </Button>
                </div>
              </div>

              {requireCaptcha && (
                <div>
                  <TurnstileCaptcha
                    key={signInCaptchaKey}
                    onSuccess={setSignInCaptchaToken}
                    onError={() => setSignInCaptchaToken(null)}
                    onExpire={() => setSignInCaptchaToken(null)}
                    siteKey={import.meta.env.VITE_TURNSTILE_SITE_KEY}
                    theme="auto"
                  />
                </div>
              )}

              <Button 
                type="submit" 
                className="w-full" 
                disabled={loading || (requireCaptcha && !signInCaptchaToken)}
              >
                {loading ? "Signing in..." : "Sign In"}
              </Button>
            </form>

            <div>
              <Button
                variant="outline"
                onClick={() => handleMagicLinkSignIn(formData.email)}
                disabled={!formData.email || magicLinkLoading}
                className="w-full"
              >
                <Zap className="w-4 h-4 mr-2" />
                {magicLinkLoading ? "Sending..." : "Send Magic Link"}
              </Button>
              <p className="text-xs text-muted-foreground mt-2 text-center">
                Enter your email above and click to receive a sign-in link
              </p>
            </div>

            <div>
              <div className="relative">
                <div className="absolute inset-0 flex items-center">
                  <Separator />
                </div>
                <div className="relative flex justify-center text-xs uppercase">
                  <span className="bg-background px-2 text-muted-foreground">
                    Or continue with
                  </span>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3 mt-4">
                <Button variant="outline" onClick={() => handleSocialSignIn('google')} className="w-full">
                  <svg className="w-4 h-4 mr-2" viewBox="0 0 24 24">
                    <path fill="currentColor" 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="currentColor" 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="currentColor" 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.93l2.85-2.22.81-.62z" />
                    <path fill="currentColor" 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>
                  Google
                </Button>
                <Button variant="outline" onClick={() => handleSocialSignIn('discord')} className="w-full">
                  <svg className="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.19.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.210 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.210 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418z" />
                  </svg>
                  Discord
                </Button>
              </div>
            </div>
              </>
            )}
          </TabsContent>

          <TabsContent value="signup" className="space-y-3 sm:space-y-4 mt-4">
            <form onSubmit={handleSignUp} className="space-y-3 sm:space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="modal-username">Username</Label>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
                    <Input
                      id="modal-username"
                      name="username"
                      placeholder="username"
                      value={formData.username}
                      onChange={handleInputChange}
                      className="pl-10"
                      required
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="modal-displayName">Display Name</Label>
                  <Input
                    id="modal-displayName"
                    name="displayName"
                    placeholder="Display Name"
                    value={formData.displayName}
                    onChange={handleInputChange}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="modal-signup-email">Email</Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
                  <Input
                    id="modal-signup-email"
                    name="email"
                    type="email"
                    placeholder="your@email.com"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="pl-10"
                    autoComplete="email"
                    required
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="modal-signup-password">Password</Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
                  <Input
                    id="modal-signup-password"
                    name="password"
                    type={showPassword ? "text" : "password"}
                    placeholder="Create a password"
                    value={formData.password}
                    onChange={handleInputChange}
                    className="pl-10 pr-10"
                    autoComplete="new-password"
                    required
                  />
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="absolute right-0 top-0 h-full px-3"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </Button>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="modal-confirmPassword">Confirm Password</Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground w-4 h-4" />
                  <Input
                    id="modal-confirmPassword"
                    name="confirmPassword"
                    type={showPassword ? "text" : "password"}
                    placeholder="Confirm your password"
                    value={formData.confirmPassword}
                    onChange={handleInputChange}
                    className="pl-10"
                    autoComplete="new-password"
                    required
                  />
                </div>
              </div>

              {requireCaptcha && (
                <div>
                  <TurnstileCaptcha
                    key={captchaKey}
                    onSuccess={setCaptchaToken}
                    onError={() => setCaptchaToken(null)}
                    onExpire={() => setCaptchaToken(null)}
                    siteKey={import.meta.env.VITE_TURNSTILE_SITE_KEY}
                    theme="auto"
                  />
                </div>
              )}

              <Button 
                type="submit" 
                className="w-full" 
                disabled={loading || (requireCaptcha && !captchaToken)}
              >
                {loading ? "Creating account..." : "Create Account"}
              </Button>
            </form>

            <div>
              <div className="relative">
                <div className="absolute inset-0 flex items-center">
                  <Separator />
                </div>
                <div className="relative flex justify-center text-xs uppercase">
                  <span className="bg-background px-2 text-muted-foreground">
                    Or continue with
                  </span>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3 mt-4">
                <Button variant="outline" onClick={() => handleSocialSignIn('google')} className="w-full" type="button">
                  <svg className="w-4 h-4 mr-2" viewBox="0 0 24 24">
                    <path fill="currentColor" 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="currentColor" 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="currentColor" 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.93l2.85-2.22.81-.62z" />
                    <path fill="currentColor" 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>
                  Google
                </Button>
                <Button variant="outline" onClick={() => handleSocialSignIn('discord')} className="w-full" type="button">
                  <svg className="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.19.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.210 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.210 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418z" />
                  </svg>
                  Discord
                </Button>
              </div>
            </div>

            <p className="text-xs text-center text-muted-foreground">
              By signing up, you agree to our{' '}
              <a href="/terms" className="underline hover:text-foreground">Terms</a>
              {' '}and{' '}
              <a href="/privacy" className="underline hover:text-foreground">Privacy Policy</a>
            </p>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
