
import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { supabase } from '@/integrations/supabase/client';
import { toast } from '@/hooks/use-toast';
import { Eye, EyeOff, ArrowLeft, Globe } from 'lucide-react';
import TermsAndConditions from '@/components/TermsAndConditions';
import { validateEmail, sanitizeString, rateLimitCheck } from '@/utils/inputValidation';
import { logFailedLogin, logSuccessfulLogin, logSuspiciousActivity } from '@/utils/securityLogger';
import { cleanupAuthState } from '@/utils/authCleanup';
import { useTranslation } from '@/hooks/useTranslation';

const AuthScreen: React.FC = () => {
  const [isLogin, setIsLogin] = useState(() => {
    const authMode = sessionStorage.getItem('auth_mode');
    if (authMode) {
      sessionStorage.removeItem('auth_mode');
      return authMode === 'login';
    }
    return true;
  });
  const [isResetPassword, setIsResetPassword] = useState(false);
  const [showTerms, setShowTerms] = useState(false);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [businessName, setBusinessName] = useState('');
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const { t, currentLanguage, changeLanguage } = useTranslation();

  const languages = [
    { code: 'en' as const, label: 'English', flag: '🇬🇧' },
    { code: 'zu' as const, label: 'IsiZulu', flag: '🇿🇦' },
    { code: 'af' as const, label: 'Afrikaans', flag: '🇿🇦' },
  ];

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateEmail(email)) {
      toast({
        title: t('common.error') || 'Invalid Email',
        description: t('signup.invalidEmail') || 'Please enter a valid email address',
        variant: 'destructive'
      });
      return;
    }

    if (!rateLimitCheck(`login_${email}`, 5, 900000)) {
      toast({
        title: t('common.error') || 'Too Many Attempts',
        description: 'Too many login attempts. Please try again later.',
        variant: 'destructive'
      });
      logSuspiciousActivity('excessive_login_attempts', { email });
      return;
    }

    setLoading(true);
    
    try {
      const { data, error } = await supabase.auth.signInWithPassword({
        email: email.toLowerCase().trim(),
        password
      });

      if (error) {
        logFailedLogin(email, error.message);
        toast({
          title: t('common.error') || 'Login Error',
          description: error.message,
          variant: 'destructive'
        });
        return;
      }

      if (data.user) {
        logSuccessfulLogin();
        // Load saved language preference
        try {
          const { data: profile } = await supabase
            .from('profiles')
            .select('language_preference')
            .eq('id', data.user.id)
            .single();
          
          if (profile?.language_preference && profile.language_preference !== currentLanguage) {
            changeLanguage(profile.language_preference as any);
          }
        } catch {}

        toast({
          title: t('auth.welcomeBack') || 'Welcome back!',
          description: t('signup.loginSuccess') || 'Successfully logged in to HustleBoss.'
        });
      }
    } catch (error) {
      console.error('Login error:', error);
      logFailedLogin(email, 'Unexpected error during login');
      toast({
        title: t('common.error') || 'Error',
        description: 'An unexpected error occurred',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSignUp = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateEmail(email)) {
      toast({
        title: t('common.error') || 'Invalid Email',
        description: t('signup.invalidEmail') || 'Please enter a valid email address',
        variant: 'destructive'
      });
      return;
    }

    if (!firstName.trim() || firstName.length > 50) {
      toast({
        title: t('common.error') || 'Invalid First Name',
        description: 'First name must be 1-50 characters',
        variant: 'destructive'
      });
      return;
    }

    if (!lastName.trim() || lastName.length > 50) {
      toast({
        title: t('common.error') || 'Invalid Last Name',
        description: 'Last name must be 1-50 characters',
        variant: 'destructive'
      });
      return;
    }

    if (!businessName.trim() || businessName.length > 100) {
      toast({
        title: t('common.error') || 'Invalid Business Name',
        description: 'Business name must be 1-100 characters',
        variant: 'destructive'
      });
      return;
    }

    if (!termsAccepted) {
      toast({
        title: t('common.error') || 'Terms Required',
        description: t('signup.termsRequired') || 'Please accept the Terms and Conditions to continue',
        variant: 'destructive'
      });
      return;
    }

    if (password.length < 8) {
      toast({
        title: t('common.error') || 'Password Too Short',
        description: t('signup.passwordHint') || 'Password must be at least 8 characters long',
        variant: 'destructive'
      });
      return;
    }

    if (password !== confirmPassword) {
      toast({
        title: t('common.error') || 'Passwords Don\'t Match',
        description: t('signup.passwordMismatch') || 'Please ensure both passwords are identical',
        variant: 'destructive'
      });
      return;
    }

    if (!rateLimitCheck(`signup_${email}`, 3, 3600000)) {
      toast({
        title: t('common.error') || 'Too Many Attempts',
        description: 'Too many signup attempts. Please try again later.',
        variant: 'destructive'
      });
      return;
    }
    
    setLoading(true);
    
    try {
      cleanupAuthState();
      try { await supabase.auth.signOut({ scope: 'global' }); } catch {}

      const redirectUrl = `${window.location.origin}/email-confirmation`;

      const attemptSignUp = async (withMeta: boolean) => {
        return await supabase.auth.signUp({
          email: email.toLowerCase().trim(),
          password,
          options: withMeta ? {
            emailRedirectTo: redirectUrl,
            data: {
              first_name: sanitizeString(firstName),
              last_name: sanitizeString(lastName),
              business_name: sanitizeString(businessName),
              language_preference: currentLanguage
            }
          } : {
            emailRedirectTo: redirectUrl
          }
        });
      };

      const minimalAttempt = async () => {
        return await supabase.auth.signUp({
          email: email.toLowerCase().trim(),
          password
        });
      };

      const isDbError = (err: any) => String(err?.message || err).toLowerCase().includes('database error');

      let data: any | null = null;
      let error: any | null = null;

      ({ data, error } = await attemptSignUp(true));

      if (error && isDbError(error)) {
        ({ data, error } = await attemptSignUp(false));
      }

      if (error && isDbError(error)) {
        ({ data, error } = await minimalAttempt());
      }

      if (error) {
        console.error('Sign up failed:', error);
        toast({
          title: t('common.error') || 'Sign Up Error',
          description: error.message || 'Unable to create account. Please try again.',
          variant: 'destructive'
        });
        return;
      }

      if (data?.user) {
        // Save language preference to profile
        try {
          await supabase
            .from('profiles')
            .update({ language_preference: currentLanguage })
            .eq('id', data.user.id);
        } catch {}

        toast({
          title: t('common.success') || 'Account Created! 🎉',
          description: t('signup.checkEmail') || 'Please check your email to confirm your account.'
        });
        setIsLogin(true);
      }
    } catch (error) {
      console.error('Sign up error:', error);
      toast({
        title: t('common.error') || 'Error',
        description: 'An unexpected error occurred',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordReset = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!email) {
      toast({
        title: t('common.error') || 'Email Required',
        description: t('signup.emailRequired') || 'Please enter your email address',
        variant: 'destructive'
      });
      return;
    }
    
    setLoading(true);
    
    try {
      const { error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: `${window.location.origin}/password-reset`
      });

      if (error) {
        toast({
          title: t('common.error') || 'Reset Error',
          description: error.message,
          variant: 'destructive'
        });
        return;
      }

      toast({
        title: t('signup.resetEmailSent') || 'Reset Email Sent! 📧',
        description: t('signup.checkEmailReset') || 'Check your email for password reset instructions'
      });
      setIsResetPassword(false);
    } catch (error) {
      console.error('Password reset error:', error);
      toast({
        title: t('common.error') || 'Error',
        description: 'An unexpected error occurred',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  if (showTerms) {
    return <TermsAndConditions onBack={() => setShowTerms(false)} />;
  }

  const LanguagePickerHeader = () => (
    <div className="w-full mb-4">
      <div className="flex items-center justify-center gap-2 mb-2">
        <Globe className="w-4 h-4 text-primary" />
        <span className="text-sm font-medium text-foreground">
          {t('signup.chooseLanguage') || 'Choose your language'} / Khetha ulimi lwakho / Kies jou taal
        </span>
      </div>
      <div className="flex justify-center gap-2">
        {languages.map((lang) => (
          <Button
            key={lang.code}
            variant={currentLanguage === lang.code ? 'default' : 'outline'}
            size="sm"
            onClick={() => changeLanguage(lang.code)}
            className="text-xs"
          >
            {lang.flag} {lang.label}
          </Button>
        ))}
      </div>
    </div>
  );

  return (
    <div className="flex items-center justify-center min-h-screen p-4 bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-900 dark:to-slate-800">
      <div className="w-full max-w-md">
        <Card className="shadow-xl">
          <CardHeader className="text-center bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-t-lg">
            <div className="flex justify-center mb-4">
              <img 
                src="/hustleboss-logo-optimized.webp" 
                alt="HustleBoss Logo" 
                className="w-16 h-16 rounded-full shadow-lg border-4 border-white"
                width="64"
                height="64"
              />
            </div>
            <CardTitle className="text-2xl font-bold">HustleBoss</CardTitle>
            <CardDescription className="text-blue-100">
              {t('signup.empoweringSA') || 'Empowering SA Small Businesses'}
            </CardDescription>
          </CardHeader>
          
          <CardContent className="p-6">
            {/* Prominent Language Selector */}
            <LanguagePickerHeader />

            {isResetPassword ? (
              <div>
                <div className="flex items-center mb-4">
                  <Button variant="ghost" size="sm" onClick={() => setIsResetPassword(false)}>
                    <ArrowLeft className="w-4 h-4 mr-1" />
                    {t('common.back') || 'Back'}
                  </Button>
                </div>
                <form onSubmit={handlePasswordReset} className="space-y-4">
                  <div>
                    <Label htmlFor="reset-email">{t('signup.emailAddress') || 'Email Address'}</Label>
                    <Input
                      id="reset-email"
                      type="email"
                      placeholder={t('signup.emailAddress') || 'Enter your email'}
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required
                    />
                  </div>
                  <Button type="submit" className="w-full" disabled={loading}>
                    {loading ? (t('signup.sendingReset') || 'Sending...') : (t('signup.resetPasswordTitle') || 'Reset Password')}
                  </Button>
                </form>
              </div>
            ) : !isLogin ? (
              <div>
                <h3 className="text-lg font-semibold mb-4">{t('signup.createYourAccount') || 'Create Your Account'}</h3>
                <form onSubmit={handleSignUp} className="space-y-4">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <Label htmlFor="firstName">{t('signup.firstName') || 'First Name'}</Label>
                      <Input
                        id="firstName"
                        type="text"
                        placeholder={t('signup.firstName') || 'John'}
                        value={firstName}
                        onChange={(e) => setFirstName(e.target.value)}
                        required
                      />
                    </div>
                    <div>
                      <Label htmlFor="lastName">{t('signup.lastName') || 'Last Name'}</Label>
                      <Input
                        id="lastName"
                        type="text"
                        placeholder={t('signup.lastName') || 'Doe'}
                        value={lastName}
                        onChange={(e) => setLastName(e.target.value)}
                        required
                      />
                    </div>
                  </div>
                  
                  <div>
                    <Label htmlFor="businessName">{t('signup.businessName') || 'Business Name'}</Label>
                    <Input
                      id="businessName"
                      type="text"
                      placeholder={t('signup.businessName') || 'Acme Inc.'}
                      value={businessName}
                      onChange={(e) => setBusinessName(e.target.value)}
                      required
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="signup-email">{t('signup.emailAddress') || 'Email'}</Label>
                    <Input
                      id="signup-email"
                      type="email"
                      placeholder="john.doe@example.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="signup-password">{t('signup.createPassword') || 'Password'}</Label>
                    <div className="relative">
                      <Input
                        id="signup-password"
                        type={showPassword ? "text" : "password"}
                        placeholder={t('signup.passwordHint') || '••••••••'}
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                        minLength={6}
                        className="pr-10"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3"
                        onClick={() => setShowPassword(!showPassword)}
                      >
                        {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                    </div>
                  </div>
                  
                  <div>
                    <Label htmlFor="confirm-password">{t('signup.confirmPassword') || 'Confirm Password'}</Label>
                    <Input
                      id="confirm-password"
                      type="password"
                      placeholder="••••••••"
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      required
                    />
                  </div>
                  
                  <div className="flex items-start space-x-2">
                    <Checkbox
                      id="terms"
                      checked={termsAccepted}
                      onCheckedChange={(checked) => setTermsAccepted(!!checked)}
                    />
                    <Label htmlFor="terms" className="text-sm leading-relaxed">
                      {t('signup.agreeToTerms') || 'I agree to the'}{' '}
                      <button 
                        type="button" 
                        className="text-blue-600 underline hover:text-blue-800"
                        onClick={() => setShowTerms(true)}
                      >
                        {t('signup.termsLink') || 'Terms and Conditions'}
                      </button>
                      {' '}{t('signup.andPrivacy') || 'and Privacy Policy'}
                    </Label>
                  </div>
                  
                  <Button 
                    type="submit" 
                    className="w-full bg-gradient-to-r from-blue-600 to-purple-600" 
                    disabled={loading || !termsAccepted}
                  >
                    {loading ? (t('signup.creatingAccount') || 'Creating Account...') : (t('signup.createAccount') || 'Create Account')}
                  </Button>
                </form>
                
                <div className="mt-4 text-center">
                  <Button variant="link" onClick={() => setIsLogin(true)}>
                    {t('signup.hasAccount') || 'Already have an account?'} {t('signup.loginTitle') || 'Log in'}
                  </Button>
                </div>
              </div>
            ) : (
              <div>
                <h3 className="text-lg font-semibold mb-4">{t('signup.signInTitle') || 'Sign In to Your Account'}</h3>
                <form onSubmit={handleLogin} className="space-y-4">
                  <div>
                    <Label htmlFor="email">{t('signup.emailAddress') || 'Email'}</Label>
                    <Input
                      id="email"
                      type="email"
                      placeholder="your@email.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      required
                    />
                  </div>
                  <div>
                    <Label htmlFor="password">{t('signup.createPassword') || 'Password'}</Label>
                    <div className="relative">
                      <Input
                        id="password"
                        type={showPassword ? "text" : "password"}
                        placeholder="••••••••"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        required
                        className="pr-10"
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3"
                        onClick={() => setShowPassword(!showPassword)}
                      >
                        {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                    </div>
                  </div>
                  <Button 
                    type="submit" 
                    className="w-full bg-gradient-to-r from-blue-600 to-purple-600" 
                    disabled={loading}
                  >
                    {loading ? (t('signup.loggingIn') || 'Logging in...') : (t('signup.loginTitle') || 'Log In')}
                  </Button>
                </form>
                
                <div className="mt-4 text-center space-y-2">
                  <Button variant="link" size="sm" onClick={() => setIsResetPassword(true)}>
                    {t('signup.forgotPassword') || 'Forgot Password?'}
                  </Button>
                  <div>
                    <Button variant="link" onClick={() => setIsLogin(false)}>
                      {t('signup.noAccount') || "Don't have an account?"} {t('signup.signUpLink') || 'Sign up'}
                    </Button>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
};

export default AuthScreen;
