"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useRequestOTP, useVerifyLoginOTP } from "@/hooks/api/useAuthMutations";
import { Phone, ShieldCheck, ChevronRight, User as UserIcon, Lock, Mail, ArrowLeft } from "lucide-react";

type AuthMode = "signin" | "signup";
type LoginMethod = "otp" | "password";
type UserType = "seeker" | "employer";

export default function ModernAuthModal() {
  const router = useRouter();

  const [step, setStep] = useState(1); // 1 = Phone/Details, 2 = OTP
  const [phone, setPhone] = useState("");
  const [otp, setOtp] = useState("");
  
  const [error, setError] = useState("");

  const requestOtpMutation = useRequestOTP();
  const verifyOtpMutation = useVerifyLoginOTP();

  const handleSendOtp = (e: React.FormEvent) => {
    e.preventDefault();
    if (phone.length < 10) {
      setError("Please enter a valid phone number.");
      return;
    }
    setError("");

    requestOtpMutation.mutate(
      { phone, role: 'seeker' },
      {
        onSuccess: () => {
          setStep(2);
        },
        onError: (err: any) => {
          setError(err.response?.data?.message || "Failed to send OTP. Please try again.");
        }
      }
    );
  };

  const handleVerifyOtp = (e: React.FormEvent) => {
    e.preventDefault();
    if (otp.length < 4) {
      setError("Please enter a valid OTP.");
      return;
    }
    setError("");

    verifyOtpMutation.mutate(
      { phone, otp, role: 'seeker' },
      {
        onSuccess: (data) => {
          if (data.onboarding_status === 'pending') {
            router.push('/seeker/onboarding');
          } else if (data.redirect) {
            router.push(data.redirect);
          } else {
            router.push('/seeker/dashboard');
          }
        },
        onError: (err: any) => {
          setError(err.response?.data?.message || "Invalid OTP. Please try again.");
        }
      }
    );
  };

  const loading = requestOtpMutation.isPending || verifyOtpMutation.isPending;

  return (
    <div className="w-full max-w-[400px]">
      <div className="mb-8 text-center lg:text-left">
        <h2 className="text-2xl font-bold text-gray-900">
          {step === 1 ? "Sign In" : "Verify OTP"}
        </h2>
        <p className="text-gray-500 text-sm mt-2">
          {step === 1 ? "Welcome back! Please enter your phone number." : `We've sent a code to +91 ${phone}`}
        </p>
      </div>

      {error && (
        <div className="mb-6 p-3 bg-red-50 text-red-600 text-sm rounded-md border border-red-100 flex items-center">
          <span>{error}</span>
        </div>
      )}

      {step === 1 && (
        <form onSubmit={handleSendOtp} className="space-y-5">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Phone Number</label>
            <div className="flex items-center px-3 py-2.5 rounded-md border border-gray-200 bg-white focus-within:border-[#ff6b00] focus-within:ring-1 focus-within:ring-[#ff6b00]/30 transition-all">
              <span className="text-gray-500 mr-2 pr-2 border-r border-gray-200">+91</span>
              <input
                type="tel"
                value={phone}
                onChange={(e) => setPhone(e.target.value.replace(/\D/g, ''))}
                maxLength={10}
                placeholder="Enter your mobile number"
                className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                required
              />
              <Phone className="w-4 h-4 text-gray-400 ml-2" />
            </div>
          </div>

          <button
            type="submit"
            disabled={loading || phone.length < 10}
            className="w-full py-3 bg-[#ff6b00] text-white font-medium rounded-md hover:bg-[#e65a00] focus:ring-4 focus:ring-[#ff6b00]/20 transition-all flex justify-center items-center disabled:opacity-70 disabled:cursor-not-allowed"
          >
            {loading ? (
              <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
            ) : (
              <>Send OTP <ChevronRight className="w-4 h-4 ml-1.5" /></>
            )}
          </button>
        </form>
      )}

      {step === 2 && (
        <form onSubmit={handleVerifyOtp} className="space-y-5">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">Secure OTP</label>
            <div className="flex items-center px-3 py-2.5 rounded-md border border-gray-200 bg-white focus-within:border-[#ff6b00] focus-within:ring-1 focus-within:ring-[#ff6b00]/30 transition-all">
              <ShieldCheck className="w-4 h-4 text-[#ff6b00] mr-2" />
              <input
                type="text"
                value={otp}
                onChange={(e) => setOtp(e.target.value)}
                maxLength={6}
                placeholder="Enter 6-digit OTP"
                className="w-full text-sm outline-none bg-transparent text-gray-800 tracking-widest placeholder:tracking-normal placeholder:text-gray-400 font-medium"
                required
                autoFocus
              />
            </div>
          </div>
          
          <div className="flex flex-col gap-3">
            <button
              type="submit"
              disabled={loading || otp.length < 4}
              className="w-full py-3 bg-[#ff6b00] text-white font-medium rounded-md hover:bg-[#e65a00] transition-all flex justify-center items-center disabled:opacity-70"
            >
              {loading ? <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : "Verify & Login"}
            </button>

            <button
              type="button"
              onClick={() => { setStep(1); setOtp(""); setError(""); }}
              className="w-full py-3 bg-white border border-gray-200 text-gray-600 font-medium rounded-md hover:bg-gray-50 flex justify-center items-center"
            >
              <ArrowLeft className="w-4 h-4 mr-1.5" /> Back
            </button>
          </div>
        </form>
      )}
    </div>
  );
}
