"use client";

import { useState, useRef, useEffect } from "react";
import Image from "next/image";
import { ArrowLeft, X, User } from "lucide-react";
import { api } from "@/services/api";
import { useRouter } from "next/navigation";
import { useAuthStore } from "@/store/auth.store";
import Link from "next/link";

interface CandidateAuthModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export function CandidateAuthModal({ isOpen, onClose }: CandidateAuthModalProps) {
  const [step, setStep] = useState<'PHONE' | 'REGISTER_PROMPT' | 'OTP'>('PHONE');
  const [authMode, setAuthMode] = useState<'login' | 'register'>('login');
  const [phone, setPhone] = useState('');
  const [otp, setOtp] = useState(['', '', '', '']);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [timer, setTimer] = useState(60);
  const router = useRouter();
  const { setAuth } = useAuthStore();

  const otpRefs = [
    useRef<HTMLInputElement>(null),
    useRef<HTMLInputElement>(null),
    useRef<HTMLInputElement>(null),
    useRef<HTMLInputElement>(null)
  ];

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (step === 'OTP' && timer > 0) {
      interval = setInterval(() => {
        setTimer((prev) => prev - 1);
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [step, timer]);

  if (!isOpen) return null;

  const handlePhoneSubmit = async () => {
    if (phone.length < 10) {
      setError('Please enter a valid 10-digit mobile number');
      return;
    }
    setError('');
    setLoading(true);
    try {
      // 1. Check if user exists
      const { data } = await api.post('/users/check_phone', { phone });

      // If exists is true, verify they actually have the 'seeker' role
      const isSeeker = data.exists && Array.isArray(data.roles) && data.roles.some((r: any) => r.role === 'seeker');

      if (isSeeker) {
        // Login flow
        await api.post('/users/send_otp_for_role', { phone, role: 'seeker' });
        setAuthMode('login');
        setStep('OTP');
        setTimer(60);
      } else {
        // Show Registration Prompt
        setStep('REGISTER_PROMPT');
      }
    } catch (err: any) {
      setError(err.response?.data?.message || 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  const handleRegisterConfirm = async () => {
    setError('');
    setLoading(true);
    try {
      await api.post('/users/send_registration_otp', { phone, role: 'seeker' });
      setAuthMode('register');
      setStep('OTP');
      setTimer(60);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  const handleOtpSubmit = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    const otpValue = otp.join('');
    if (otpValue.length < 4) {
      setError('Please enter complete OTP');
      return;
    }
    setError('');
    setLoading(true);
    try {
      if (authMode === 'login') {
        const { data } = await api.post('/users/verify_otp_and_login', {
          phone,
          otp: otpValue,
          role: 'seeker'
        });

        // Update store with just tokens
        if (data && data.access_token) {
          const userObj = data.user || {
            id: data.id,
            name: data.name || data.first_name || '',
            email: data.email || '',
            phone: data.phone || '',
            role: data.role || 'seeker',
            onboarding_status: data.onboarding_status,
            onboarding_step: data.onboarding_step
          };
          setAuth(userObj, data.access_token, data.refresh_token);
          
          onClose();
          if (data.onboarding_status === 'pending') {
            router.push('/seeker/onboarding');
          } else if (data.redirect) {
            router.push(data.redirect);
          } else {
            router.push('/seeker/dashboard');
          }
        } else {
          setError('Invalid response from server');
        }
      } else {
        // Registration Mode: Verify OTP then go to onboarding
        const { data } = await api.post('/users/verify_registration_otp', {
          phone,
          otp: otpValue,
          role: 'seeker'
        });

        if (data && data.access_token) {
          const userObj = data.user || {
            id: data.id,
            name: data.name || data.first_name || '',
            email: data.email || '',
            phone: data.phone || '',
            role: data.role || 'seeker',
            onboarding_status: data.onboarding_status || 'pending',
            onboarding_step: data.onboarding_step
          };
          setAuth(userObj, data.access_token, data.refresh_token);
        }

        onClose();
        router.push(`/seeker/onboarding?phone=${phone}`);
      }
    } catch (err: any) {
      setError(err.response?.data?.message || 'Invalid OTP');
    } finally {
      setLoading(false);
    }
  };

  const handleResendOtp = async () => {
    setError('');
    try {
      const endpoint = authMode === 'login' ? '/users/send_otp_for_role' : '/users/send_registration_otp';
      await api.post(endpoint, { phone, role: 'seeker' });
      // Show success toast or just clear error
      setError('');
      setTimer(60);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to resend OTP');
    }
  };

  const handleOtpChange = (index: number, value: string) => {
    if (isNaN(Number(value))) return;
    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);

    // Move to next input
    if (value !== '' && index < 3) {
      otpRefs[index + 1].current?.focus();
    }
  };

  const handleOtpKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0) {
      otpRefs[index - 1].current?.focus();
    } else if (e.key === 'Enter') {
      e.preventDefault();
      if (otp.join('').length === 4 && !loading) {
        handleOtpSubmit();
      }
    }
  };

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm px-4">
      <div className="bg-white shadow-2xl w-full max-w-[900px] flex flex-col md:flex-row relative min-h-[550px] p-2 md:p-3 rounded-bl-[50px]" >
        {/* Close Button */}
        <button
          onClick={onClose}
          className="absolute right-6 top-6 z-10 p-1 text-gray-700 hover:text-black transition-colors"
        >
          <X className="h-6 w-6" strokeWidth={1.5} />
        </button>

        {/* Left Column - Orange Banner */}
        <div className="hidden md:flex flex-col bg-[#ff6b00] w-[45%] text-white pt-10 pb-0 px-10 relative overflow-hidden rounded-bl-[50px] rounded-tr-[50px]">
          {/* Background pattern */}
          <div
            className="absolute inset-0 opacity-15 pointer-events-none"
            style={{
              backgroundImage:
                "repeating-linear-gradient(45deg, transparent, transparent 2px, white 2px, white 4px)",
            }}
          ></div>

          {/* Logo */}
          <div className="absolute top-5 left-5 z-10">
            <Image
              src="/images/jobvumi-logo.png"
              alt="Jobvumi"
              width={130}
              height={42}
              className="object-contain"
            />
          </div>

          {/* Text */}
          <div className="absolute top-24 left-5 z-10 max-w-[85%]">
            <h2 className="text-[30px] font-bold leading-[1.2] tracking-tight mb-3">
              Find the right Job,<br />
              right now.
            </h2>

            <p className="text-white/95 text-[14px] leading-relaxed">
              Join a growing community of talented professionals finding <br /> jobs with
              Jobvumi.
            </p>
          </div>

          {/* Employee Image */}
          <div className="absolute bottom-0 right-0 left-0 flex justify-center z-10">
            <div className="relative w-[110%] h-[340px] translate-y-2 translate-x-2">
              <Image
                src="/images/login_employee.png"
                alt="Professional"
                fill
                sizes="(max-width: 768px) 100vw, 50vw"
                className="object-contain object-bottom"
                priority
              />
            </div>
          </div>
        </div>

        {/* Right Column - Form */}
        <div className="w-full md:w-[55%] px-8 md:px-14 flex flex-col justify-center bg-white relative">

          {step === 'PHONE' ? (
            <div className="w-full max-w-[360px] mx-auto animate-in fade-in slide-in-from-right-4 duration-300">
              <h2 className="text-[32px] font-bold text-black mb-2 tracking-tight">Let's get started</h2>
              <p className="text-gray-700 text-[15px] mb-10">Find the Right Job Faster with Jobvumi</p>

              <div className="mb-8">
                <label className="block text-[15px] text-gray-800 mb-2 font-medium">Phone Number</label>
                <div className="flex border border-gray-300 rounded-lg overflow-hidden focus-within:border-[#ff6b00] focus-within:ring-1 focus-within:ring-[#ff6b00] transition-all">
                  <div className="bg-white px-4 py-3.5 border-r border-gray-200 flex items-center text-gray-500 font-medium">
                    +91
                  </div>
                  <input
                    type="tel"
                    placeholder="Enter 10 digit mobile number"
                    className="flex-1 px-4 py-3.5 outline-none w-full text-black placeholder-gray-400 text-[15px]"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 10))}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && phone.length === 10 && !loading) {
                        e.preventDefault();
                        handlePhoneSubmit();
                      }
                    }}
                    maxLength={10}
                  />
                </div>
                {error && <p className="text-red-500 text-xs mt-2">{error}</p>}
              </div>

              <button
                onClick={handlePhoneSubmit}
                disabled={loading || phone.length < 10}
                className="w-full bg-[#ff6b00] hover:bg-[#E6501A] disabled:opacity-70 disabled:cursor-not-allowed text-white font-medium py-3.5 rounded-lg transition-colors text-[16px]"
              >
                {loading ? 'Processing...' : 'Continue'}
              </button>

              <div className="mt-8 text-center px-4">
                <p className="text-[13px] text-black font-medium leading-relaxed">
                  I agree to <Link href="/terms" className="text-[#ff6b00] hover:underline">Terms of Conditions</Link> & <Link href="/privacy" className="text-[#ff6b00] hover:underline">Privacy Policy</Link> of JOBVUMI
                </p>
              </div>
            </div>
          ) : step === 'REGISTER_PROMPT' ? (
            <div className="w-full max-w-[360px] mx-auto animate-in fade-in slide-in-from-right-4 duration-300 text-center">
              <button 
                onClick={() => setStep('PHONE')}
                className="mb-6 p-2 -ml-2 rounded-full hover:bg-gray-100 transition-colors text-gray-600 inline-flex items-center absolute top-6 left-6 md:relative md:top-auto md:left-auto"
              >
                <ArrowLeft className="w-5 h-5" />
              </button>
              
              <div className="bg-orange-50 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-6">
                <User className="w-8 h-8 text-[#ff6b00]" />
              </div>
              <h2 className="text-2xl font-bold text-black mb-3">Create New Account</h2>
              <p className="text-gray-500 text-sm mb-8">
                The number <span className="font-semibold text-gray-800">+91 {phone}</span> is not registered yet. Would you like to create a new account?
              </p>

              {error && <p className="text-red-500 text-xs mb-4">{error}</p>}

              <div className="flex flex-col gap-3">
                <button
                  onClick={handleRegisterConfirm}
                  disabled={loading}
                  className="w-full bg-[#ff6b00] text-white py-3.5 rounded-lg font-medium hover:bg-[#e66000] transition-colors disabled:opacity-70 flex justify-center items-center h-[52px]"
                >
                  {loading ? (
                    <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  ) : (
                    "Yes, Register Now"
                  )}
                </button>
                <button
                  onClick={() => setStep('PHONE')}
                  disabled={loading}
                  className="w-full bg-gray-100 text-gray-700 py-3.5 rounded-lg font-medium hover:bg-gray-200 transition-colors disabled:opacity-70"
                >
                  Cancel
                </button>
              </div>
            </div>
          ) : (
            <div className="w-full max-w-md mx-auto animate-in fade-in slide-in-from-right-4 duration-300">
              <button
                onClick={() => setStep('PHONE')}
                className="mb-6 p-2 -ml-2 rounded-full hover:bg-gray-100 transition-colors text-gray-600 inline-flex items-center"
              >
                <ArrowLeft className="h-5 w-5" />
              </button>

              <h2 className="text-2xl font-bold text-black mb-2">Verify OTP</h2>
              <p className="text-gray-500 text-sm mb-8 flex items-center gap-2">
                Enter the 4-digit code send on <br />+91-{phone}
                <button onClick={() => setStep('PHONE')} className="text-[#fc6123] hover:underline ml-1">
                  ✎
                </button>
              </p>

              <div className="flex justify-between gap-3 mb-6">
                {[0, 1, 2, 3].map((index) => (
                  <input
                    key={index}
                    ref={otpRefs[index]}
                    type="text"
                    maxLength={1}
                    value={otp[index]}
                    onChange={(e) => handleOtpChange(index, e.target.value)}
                    onKeyDown={(e) => handleOtpKeyDown(index, e)}
                    className="w-14 h-14 text-center text-xl font-semibold border border-gray-300 rounded-lg focus:border-[#ff7300] focus:ring-1 focus:ring-[#ff7300] outline-none transition-all shadow-sm"
                  />
                ))}
              </div>

              {error && <p className="text-red-500 text-xs mt-1 mb-4 text-center">{error}</p>}

              <div className="text-center mb-6">
                <p className="text-gray-500 text-sm font-medium">00:{timer.toString().padStart(2, '0')}</p>
                <p className="text-sm mt-1">
                  <span className="text-gray-500">Didn't get the OTP? </span>
                  {timer === 0 ? (
                    <button onClick={handleResendOtp} className="text-[#fc6123] font-medium hover:underline">
                      Resend
                    </button>
                  ) : (
                    <span className="text-gray-400">Resend</span>
                  )}
                </p>
              </div>

              <button
                onClick={handleOtpSubmit}
                disabled={loading || otp.join('').length < 4}
                className="w-full bg-[#fc6123] hover:bg-[#E6501A] disabled:opacity-70 disabled:cursor-not-allowed text-white font-semibold py-3.5 rounded-lg transition-colors shadow-md shadow-orange-200"
              >
                {loading ? 'Verifying...' : 'Continue'}
              </button>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}
