//  components/common/AuthModal.tsx

"use client";

import { useState } from "react";
import { useAppDispatch } from "@/store/hooks";
import { sendOTP, verifyOTP, register } from "@/features/auth/authSlice";

interface Props {
  open: boolean;
  onClose: () => void;
}

export default function AuthModal({ open, onClose }: Props) {
  const dispatch = useAppDispatch();

  const [step, setStep] = useState<"phone" | "otp" | "register">("phone");
  const [phone, setPhone] = useState("");
  const [otp, setOtp] = useState("");

  const [form, setForm] = useState({
    full_name: "",
    email: "",
    nationality: "Indian",
    dl_origin: "Indian",
  });

  if (!open) return null;

  // ✅ SEND OTP
  const handleSendOtp = async () => {
    const res: any = await dispatch(sendOTP(phone));

    if (res.payload?.isRegistered) {
      setStep("otp");
    } else {
      setStep("register");
    }
  };

  // ✅ REGISTER + OTP
  const handleRegister = async () => {
    await dispatch(
      register({
        phone_number: phone,
        alternate_phone_number: phone,
        ...form,
      })
    );
    setStep("otp");
  };

  // ✅ VERIFY OTP (LOGIN)
  const handleVerifyOtp = async () => {
    const res: any = await dispatch(
      verifyOTP({
        phone_number: phone,
        otp,
      })
    );

    if (res.payload?.access_token) {
  onClose();
}
  };

  



  return (
    <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 px-4">
      <div className="bg-white w-full max-w-md rounded-xl p-6 relative">

        {/* Close */}
        <button onClick={onClose} className="absolute right-4 top-4">
          ✕
        </button>

        {/* STEP 1: PHONE */}
        {step === "phone" && (
          <>
            <h2 className="text-xl font-semibold mb-4">Login / Signup</h2>

            <input
              type="text"
              placeholder="Enter phone number"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              className="w-full border p-3 rounded mb-4"
            />

            <button
              onClick={handleSendOtp}
              className="w-full bg-orange-500 text-white py-3 rounded"
            >
              Send OTP
            </button>
          </>
        )}

        {/* STEP 2: REGISTER */}
        {step === "register" && (
          <>
            <h2 className="text-xl font-semibold mb-4">Complete Profile</h2>

            <input
              placeholder="Full Name"
              className="w-full border p-3 rounded mb-3"
              onChange={(e) =>
                setForm({ ...form, full_name: e.target.value })
              }
            />

            <input
              placeholder="Email"
              className="w-full border p-3 rounded mb-3"
              onChange={(e) =>
                setForm({ ...form, email: e.target.value })
              }
            />

            <button
              onClick={handleRegister}
              className="w-full bg-orange-500 text-white py-3 rounded"
            >
              Register & Send OTP
            </button>
          </>
        )}

        {/* STEP 3: OTP */}
        {step === "otp" && (
          <>
            <h2 className="text-xl font-semibold mb-4">
              Enter OTP sent to {phone}
            </h2>

            <input
              placeholder="Enter OTP"
              value={otp}
              onChange={(e) => setOtp(e.target.value)}
              className="w-full border p-3 rounded mb-4"
            />

            <button
              onClick={handleVerifyOtp}
              className="w-full bg-orange-500 text-white py-3 rounded"
            >
              Verify & Login
            </button>
          </>
        )}
      </div>
    </div>
  );
}