import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { Mail, ArrowLeft, Loader2, Edit2 } from "lucide-react";
import { useNavigate, useLocation } from "react-router-dom";
import { API_URL } from "@/lib/config";
import { useTranslation } from "react-i18next";

const OTP = () => {
  const { t } = useTranslation();
  const [otp, setOtp] = useState("");
  const navigate = useNavigate();
  const location = useLocation();
  const [error, setError] = useState("");
  const [isVerifying, setIsVerifying] = useState(false);
  const [isResending, setIsResending] = useState(false);
  console.log(location.state);
  // Route guard: Check if user accessed this page properly
  useEffect(() => {
    // Check if the user came from a proper flow (signup/login with OTP request)
    // This checks for location state which should be passed when navigating to OTP
    const isValidAccess = location.state?.fromEmailVerification ||
      location.state?.fromSignup ||
      location.state?.email;

    if (!isValidAccess) {
      // If no valid state found, redirect to login
      console.warn("Direct access to OTP page detected. Redirecting to login.");
      navigate("/login", { replace: true });
      return;
    }
  }, [location.state, navigate]);

  const handleVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsVerifying(true);
    setError(""); // Clear any previous errors
    
    try {
      // For now, just redirect to dashboard after verification
      // In a real app, this would verify the OTP
      ///auth/signup/verify
      const response = await fetch(`${API_URL}/auth/signup/verify`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ otp: otp, signupId: location.state?.signupId }),
      });
      // if response.json() => success == true navigate to login page 
      const data = await response.json();
      if (data.success) {
        navigate("/login");
        return;
      }
      // data.error == "User already registered" navigate to login page
      if (data.error == "User already registered") {
        navigate("/login");
        return;
      }
      // data.error == "Invalid OTP" show error message
      if (data.error == "Invalid OTP code") {
        setError(t('otp.errors.invalidOTP'));
      }
      else {
        setError(t('otp.errors.somethingWrong'));
      }

      console.log("OTP verification:", { otp });
    } catch (error) {
      console.error("OTP verification error:", error);
      setError(t('otp.errors.somethingWrong'));
    } finally {
      setIsVerifying(false);
    }
  };

  const handleResend = async () => {
    setIsResending(true);
    setError(""); // Clear any previous errors
    
    try {
      const response = await fetch(`${API_URL}/auth/signup/resend-otp`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ signupId: location.state?.signupId }),
      });
      
      const data = await response.json();
      if (data.success) {
        // Show success message or just clear any errors
        console.log("OTP resent successfully");
        // Optionally show a success message to user
      } else {
        setError(data.error || t('otp.errors.somethingWrong'));
      }
    } catch (error) {
      console.error("Resend OTP error:", error);
      setError(t('otp.errors.somethingWrong'));
    } finally {
      setIsResending(false);
    }
  };

  // Show loading or nothing while checking access
  if (!location.state?.fromEmailVerification &&
    !location.state?.fromSignup &&
    !location.state?.email) {
    return null; // Component will unmount due to navigation in useEffect
  }

  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('otp.subtitle')}</p>
        </div>

        <Card className="bg-slate-800 border-slate-700">
          <CardHeader>
            <CardTitle className="text-white text-center">{t('otp.title')}</CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleVerify} className="space-y-6">
              <div className="space-y-4">
                <div className="flex items-center justify-center">
                  <div className="w-16 h-16 bg-cyan-500/20 rounded-full flex items-center justify-center mb-4">
                    <Mail className="h-8 w-8 text-cyan-400" />
                  </div>
                </div>

                <div className="text-center">
                  <p className="text-slate-300 text-sm mb-2">
                    {t('otp.sentTo')}
                  </p>
                  <div className="flex items-center justify-center gap-2">
                    <p className="text-white font-medium">
                      {location.state?.email ?
                        location.state.email.replace(/(.{1,3}).+@/, '$1***@') :
                        'user@••••••.com'
                      }
                    </p>
                    <button
                      onClick={() => navigate("/signup", {
                        state: {
                          ...location.state,
                          editingEmail: true
                        }
                      })}
                      className="ml-2 text-cyan-400 hover:text-cyan-300 transition-colors"
                      title="Edit email address"
                    >
                      <Edit2 className="w-4 h-4" />
                    </button>
                  </div>
                  <p className="text-slate-400 text-xs mt-1">
                    {t('otp.wrongEmail')}
                  </p>
                </div>

                <div className="flex justify-center">
                  <InputOTP
                    maxLength={6}
                    value={otp}
                    onChange={(value) => {
                      setOtp(value);
                      // Clear error when user starts typing new OTP
                      if (error) setError("");
                    }}
                  >
                    <InputOTPGroup>
                      <InputOTPSlot index={0} className="bg-slate-700 border-slate-600 text-white" />
                      <InputOTPSlot index={1} className="bg-slate-700 border-slate-600 text-white" />
                      <InputOTPSlot index={2} className="bg-slate-700 border-slate-600 text-white" />
                      <InputOTPSlot index={3} className="bg-slate-700 border-slate-600 text-white" />
                      <InputOTPSlot index={4} className="bg-slate-700 border-slate-600 text-white" />
                      <InputOTPSlot index={5} className="bg-slate-700 border-slate-600 text-white" />
                    </InputOTPGroup>
                  </InputOTP>
                </div>

                {/* Error message display */}
                {error && (
                  <div className="text-center">
                    <p className="text-red-400 text-sm">{error}</p>
                  </div>
                )}
              </div>

              <Button
                type="submit"
                className="w-full bg-cyan-500 hover:bg-cyan-600 text-white"
                disabled={otp.length !== 6 || isVerifying}
              >
                {isVerifying ? (
                  <div className="flex items-center gap-2">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    {t('otp.verifying')}
                  </div>
                ) : (
                  t('otp.verifyCode')
                )}
              </Button>
            </form>

            <div className="mt-6 space-y-4">
              <div className="text-center">
                <p className="text-slate-400 text-sm">
                  {t('otp.didntReceive')}{" "}
                  <button
                    onClick={handleResend}
                    disabled={isResending}
                    className="text-cyan-400 hover:text-cyan-300 underline disabled:text-slate-500 disabled:cursor-not-allowed"
                  >
                    {isResending ? (
                      <span className="inline-flex items-center gap-1">
                        <Loader2 className="h-3 w-3 animate-spin" />
                        {t('otp.resending')}
                      </span>
                    ) : (
                      t('otp.resend')
                    )}
                  </button>
                </p>
              </div>

              <div className="text-center">
                <button
                  onClick={() => navigate("/login")}
                  className="inline-flex items-center gap-2 text-slate-400 hover:text-slate-300 text-sm"
                >
                  <ArrowLeft className="w-4 h-4" />
                  {t('otp.backToSignIn')}
                </button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
};

export default OTP;
