import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Phone, Mail, Lock, User, Loader2, AlertCircle } from "lucide-react";
import { useLocation, useNavigate } from "react-router-dom";
import { supabase } from "@/lib/supabase";
import { useTranslation } from "react-i18next";

const Signup = () => {
  const { t } = useTranslation();
  //if we have state and editingEmail: true we will use the state to fill the form
  const state = useLocation().state;
  const [email, setEmail] = useState(state?.form_data?.email || "");
  const [password, setPassword] = useState(state?.form_data?.password || "");
  const [name, setName] = useState(state?.form_data?.full_name || "");
  const [company, setCompany] = useState(state?.form_data?.company_name || "");
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState<{
    email?: string;
    password?: string;
    name?: string;
    company?: string;
    general?: string;
  }>({});
  const navigate = useNavigate();

  const validateEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const validatePassword = (password: string) => {
    return password.length >= 8;
  };

  const validateForm = () => {
    const newErrors: typeof errors = {};

    // Name validation
    if (!name.trim()) {
      newErrors.name = t('signup.errors.nameRequired');
    } else if (name.trim().length < 2) {
      newErrors.name = t('signup.errors.nameMinLength');
    }

    // Company validation
    if (!company.trim()) {
      newErrors.company = t('signup.errors.companyRequired');
    } else if (company.trim().length < 2) {
      newErrors.company = t('signup.errors.companyMinLength');
    }

    // Email validation
    if (!email.trim()) {
      newErrors.email = t('signup.errors.emailRequired');
    } else if (!validateEmail(email)) {
      newErrors.email = t('signup.errors.emailInvalid');
    }

    // Password validation
    if (!password) {
      newErrors.password = t('signup.errors.passwordRequired');
    } else if (!validatePassword(password)) {
      newErrors.password = t('signup.errors.passwordMinLength');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSignup = async (e: React.FormEvent) => {
    e.preventDefault();

    // Clear previous errors
    setErrors({});

    // Validate form
    if (!validateForm()) {
      return;
    }

    setIsLoading(true);
    try {
      // Use Supabase Auth SDK to sign up with email confirmation
      const { data, error } = await supabase.auth.signUp({
        email: email,
        password: password,
        options: {
          data: {
            full_name: name,
            company_name: company,
            user_name: name.toLowerCase().replace(/\s+/g, "_"),
          },
          emailRedirectTo: `${window.location.origin}/login`
        }
      });

      if (error) {
        throw error;
      }

      // Check if email confirmation is required
      if (data.user && data.user.identities && data.user.identities.length === 0) {
        // User already exists
        setErrors({
          general: t('signup.errors.emailAlreadyRegistered') || 'This email is already registered. Please login instead.'
        });
        return;
      }

      // Successfully signed up - show success message
      navigate("/login", {
        state: {
          message: t('signup.successMessage') || 'Account created successfully! Please check your email to verify your account before logging in.',
          email: email
        },
        replace: true
      });

    } catch (error: unknown) {
      console.error("Signup error:", error);
      setErrors({
        general: (error as Error)?.message || t('signup.errors.signupFailed') || 'Registration failed. Please try again.'
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-slate-900 text-white flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <div className="flex items-center justify-center gap-3 mb-4">
            <img src="/uploads/e0ddbf09-622c-426a-851f-149776e300c0.png" alt="ShopCall.ai" className="w-10 h-10" />
            <span className="text-2xl font-bold text-white">ShopCall.ai</span>
          </div>
          <p className="text-slate-400">{t('signup.subtitle')}</p>
        </div>

        <Card className="bg-slate-800 border-slate-700">
          <CardHeader>
            <CardTitle className="text-white text-center">{t('signup.title')}</CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSignup} className="space-y-4">
              {errors.general && (
                <div className="bg-red-900/20 border border-red-500/50 rounded-md p-3 flex items-center gap-2">
                  <AlertCircle className="w-4 h-4 text-red-400 flex-shrink-0" />
                  <span className="text-red-400 text-sm">{errors.general}</span>
                </div>
              )}

              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-300">{t('signup.fullName')}</label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
                  <Input
                    type="text"
                    placeholder={t('signup.fullNamePlaceholder')}
                    value={name}
                    onChange={(e) => {
                      setName(e.target.value);
                      if (errors.name) {
                        setErrors(prev => ({ ...prev, name: undefined }));
                      }
                    }}
                    className={`pl-10 bg-slate-700 border-slate-600 text-white placeholder-slate-400 ${
                      errors.name ? 'border-red-500 focus:border-red-500' : ''
                    }`}
                    disabled={isLoading}
                    required
                  />
                </div>
                {errors.name && (
                  <div className="flex items-center gap-1 text-red-400 text-sm">
                    <AlertCircle className="w-3 h-3" />
                    {errors.name}
                  </div>
                )}
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-300">{t('signup.companyName')}</label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
                  <Input
                    type="text"
                    placeholder={t('signup.companyNamePlaceholder')}
                    value={company}
                    onChange={(e) => {
                      setCompany(e.target.value);
                      if (errors.company) {
                        setErrors(prev => ({ ...prev, company: undefined }));
                      }
                    }}
                    className={`pl-10 bg-slate-700 border-slate-600 text-white placeholder-slate-400 ${
                      errors.company ? 'border-red-500 focus:border-red-500' : ''
                    }`}
                    disabled={isLoading}
                    required
                  />
                </div>
                {errors.company && (
                  <div className="flex items-center gap-1 text-red-400 text-sm">
                    <AlertCircle className="w-3 h-3" />
                    {errors.company}
                  </div>
                )}
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-300">{t('signup.email')}</label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
                  <Input
                    type="email"
                    placeholder={t('signup.emailPlaceholder')}
                    value={email}
                    onChange={(e) => {
                      setEmail(e.target.value);
                      if (errors.email) {
                        setErrors(prev => ({ ...prev, email: undefined }));
                      }
                    }}
                    className={`pl-10 bg-slate-700 border-slate-600 text-white placeholder-slate-400 ${
                      errors.email ? 'border-red-500 focus:border-red-500' : ''
                    }`}
                    disabled={isLoading}
                    required
                  />
                </div>
                {errors.email && (
                  <div className="flex items-center gap-1 text-red-400 text-sm">
                    <AlertCircle className="w-3 h-3" />
                    {errors.email}
                  </div>
                )}
              </div>

              <div className="space-y-2">
                <label className="text-sm font-medium text-slate-300">{t('signup.password')}</label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
                  <Input
                    type="password"
                    placeholder={t('signup.passwordPlaceholder')}
                    value={password}
                    onChange={(e) => {
                      setPassword(e.target.value);
                      if (errors.password) {
                        setErrors(prev => ({ ...prev, password: undefined }));
                      }
                    }}
                    className={`pl-10 bg-slate-700 border-slate-600 text-white placeholder-slate-400 ${
                      errors.password ? 'border-red-500 focus:border-red-500' : ''
                    }`}
                    disabled={isLoading}
                    required
                  />
                </div>
                {errors.password && (
                  <div className="flex items-center gap-1 text-red-400 text-sm">
                    <AlertCircle className="w-3 h-3" />
                    {errors.password}
                  </div>
                )}
                <div className="text-xs text-slate-400">
                  {t('signup.passwordRequirement')}
                </div>
              </div>

              <Button
                type="submit"
                className="w-full bg-cyan-500 hover:bg-cyan-600 text-white"
                disabled={isLoading}
              >
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    {t('signup.creatingAccount')}
                  </>
                ) : (
                  t('signup.createAccount')
                )}
              </Button>
            </form>

            <div className="mt-6 text-center">
              <p className="text-slate-400 text-sm">
                {t('signup.alreadyHaveAccount')}{" "}
                <a href="/login" className="text-cyan-400 hover:text-cyan-300">
                  {t('signup.signIn')}
                </a>
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
};

export default Signup;
