"use client";

import Image from "next/image";
import {  useRouter } from "next/navigation";
import { useState } from "react";
import { useAppDispatch } from "@/store/hooks";
import { verifyOTP } from "@/features/auth/authSlice";
import { createCustomerOrderLogin, getCustomerProfile } from "@/api/bookingApi";
import Navbar from "@/components/common/Navbar";
import { sendOTP } from "@/features/auth/authSlice";

export default function VerifyOtpPage({
  phone,
  redirect,
  order_id,
}: {
  phone: string;
  redirect: string;
  order_id: string;
}) {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [vehicle, setVehicle] = useState<"bike" | "car">("bike");
const [resending, setResending] = useState(false);
  const [otp, setOtp] = useState("");



  const handleVerify = async () => {
    const res: any = await dispatch(
      verifyOTP({
        phone_number: phone,
        otp,
      })
    );

   if (res.payload?.access_token) {
  try {
    // ✅ 1. Get customer id
    const profile = await getCustomerProfile();

    // ✅ 2. Attach customer to order (PUT/PATCH)
    if (order_id) {
      await createCustomerOrderLogin({
        order_id,
        customer_id: profile.id,
      });
    }

    // ✅ 3. Redirect back to summary (FIXED)
const finalRedirect = decodeURIComponent(redirect || "/");

// 🔥 handle double encoding
const safeRedirect = finalRedirect.includes("%7B")
  ? decodeURIComponent(finalRedirect)
  : finalRedirect;

  console.log("FINAL REDIRECT 👉", safeRedirect);

router.push(safeRedirect);
  } catch (err) {
    console.error(err);
    router.push(decodeURIComponent(redirect || "/"));
  }
}
  };

  const handleResendOtp = async () => {
  if (!phone) return;

  setResending(true);
  try {
    await dispatch(sendOTP(phone));
  } catch (err) {
    console.error(err);
  } finally {
    setResending(false);
  }
};

const handleEditPhone = () => {
  router.push(`/login?redirect=${redirect || "/"}&order_id=${order_id || ""}`);
};

return (
  <>
    {/* ✅ Navbar */}
    {/* <Navbar vehicle={vehicle} setVehicle={setVehicle} /> */}

    <div className="bg-[#ffffff] px-4 pt-6">
      <div className="max-w-6xl mx-auto flex items-center justify-center min-h-[calc(100vh-80px)]">

        <div className="w-full flex rounded-2xl overflow-hidden">

          {/* LEFT */}
          <div className="w-full md:w-1/2 p-8 md:p-12 flex flex-col justify-center">

            {/* Heading */}
            <h2 className="text-3xl md:text-4xl font-bold text-[#2D2D2D] mb-4">
              Welcome Riders 👋
            </h2>

            <p className="text-gray-500 mb-6 text-sm">
              Today is a new day. It’s your day. <br />
              Eat, Sleep, Ride, Repeat!
            </p>

            {/* OTP Info */}
            <p className="text-sm text-gray-500 mb-2">
              OTP sent to {phone}.{" "}
              <span
                onClick={handleEditPhone}
                className="text-primary cursor-pointer font-medium"
              >
                Edit here.
              </span>
            </p>

            {/* OTP INPUT */}
            <label className="text-xs text-gray-400 mb-2">
              Enter OTP
            </label>

            <input
              type="text"
              placeholder="-----"
              value={otp}
              onChange={(e) => setOtp(e.target.value)}
              className="w-full bg-gray-100 px-4 py-3 rounded-lg mb-2 outline-none"
            />

            {/* RESEND */}
            <div className="text-right mb-5">
              <button
                onClick={handleResendOtp}
                disabled={resending}
                className="text-sm text-gray-500 hover:text-primary"
              >
                {resending ? "Resending..." : "Resend"}
              </button>
            </div>

            {/* VERIFY BUTTON */}
            <button
              onClick={handleVerify}
              className="w-full bg-primary text-white py-3 rounded-lg font-medium hover:opacity-90"
            >
              Login
            </button>
          </div>

          {/* RIGHT IMAGE */}
          <div className="hidden md:flex w-1/2 items-center justify-center p-6">
            <div className="relative w-[420px] h-[520px]">
              <Image
                src="/auth-bike.webp"
                alt="Bike"
                fill
                className="object-cover rounded-2xl"
              />
            </div>
          </div>

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