"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Form } from "@/components/ui/form";
import { useEffect, useState } from "react";
import apis from "@/utils/apis";
import { destroyCookie, setCookie } from "nookies";
import { useGlobalContext } from "@/context/Provider";
import { useRouter } from "next/navigation";
import Loader from "@/components/common/loader";
import { COOKIES_USER_ACCESS_TOKEN } from "@/context/actionTypes";
import AuthLayout from "@/components/layout/layout";
import { Icons } from "@/components/icons";
import authBanner from "@/assets/images/AuthImages/restaurant.png";

const formSchema = z.object({
  phone_number: z.string().min(1, "Phone number is required"),
});
type LoginForm = z.infer<typeof formSchema>;

const Login = () => {
  const res: any = sessionStorage.getItem("restaurant");
  const food: any = sessionStorage.getItem("food");
  const bank: any = sessionStorage.getItem("bank");

  const { setUserInfo, Toast, requestNotification, userInfo } = useGlobalContext();
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const form = useForm<LoginForm>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      phone_number: undefined,
    },
  });

  // Determine Step 2 visibility
  const showStep2 = (() => {
    if (!userInfo) return false;
    const { isFoodDelivery, isDineOut } = userInfo;
    const type = userInfo?.restaurant_id?.type;

    if (type !== 'food') return false;
    // Show Step 2 if Food Delivery is true OR both are false
    return isFoodDelivery || (!isFoodDelivery && !isDineOut);
  })();


  // Determine if Step 3 should appear active
  const isStep3Active = (() => {
    // Step 3 is active if Step 1 is complete and either:
    // 1. Step 2 is shown and completed (food === "complete")
    // 2. Step 2 is hidden (showStep2 === false)
    if (res !== "complete") return false;
    if (!showStep2) return true;
    return food === "complete";
  })();



  const [showPasswords, setShowPasswords] = useState({
    old: false,
    new: false,
    confirm: false,
  });

  function getDeviceType() {
    const userAgent = navigator.userAgent.toLowerCase();
    const width = window.screen.width;
    const height = window.screen.height;
    if (/mobile/i.test(userAgent)) {
      return "mobile";
    } else if (/tablet/i.test(userAgent)) {
      return "tablet";
    } else if (width > 1024 && height <= 800) {
      return "laptop";
    } else {
      return "computer";
    }
  }

  const onSubmit = async (data: LoginForm) => {
    setUserInfo(null);
    apis.setToken("");
    destroyCookie(null, COOKIES_USER_ACCESS_TOKEN, {
      maxAge: 0,
      path: "/",
    });
    try {
      let payload: any = {
        ...data,
        device_type: "WEB",
      };
      setLoading(true);
      const fcm_token = await requestNotification();
      if (fcm_token) {
        payload["fcm_token"] = fcm_token;
      }
      const system_type = getDeviceType();
      if (system_type) {
        payload["system_type"] = system_type;
      }
      const apiRes = await apis.Auth.login(payload);
      if (!apiRes?.data?.is_email_verified) {
        router.replace(
          `/auth/verify/email?email=${apiRes?.data?.email}&key=${apiRes?.data?.unique_string}`
        );
      } else {
        apis.setToken(apiRes?.data?.access_token);
        setCookie(null, "COOKIES_USER_ACCESS_TOKEN", apiRes?.data?.access_token, {
          path: "/",
        });
        setUserInfo({
          ...apiRes?.data,
          access_token: apiRes?.data?.access_token,
        });
        router.replace("/dashboard");
      }
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    let token: any = sessionStorage.getItem("token");
    if (!token) {
      router.replace(`/auth/login`);
    }
  }, []);

  const togglePasswordVisibility = (field: keyof typeof showPasswords) => {
    setShowPasswords((prev) => ({
      ...prev,
      [field]: !prev[field],
    }));
  };

  const handleSubmit = async () => {
    try {
      const apiRes = await apis.Auth.Submit();
      if (apiRes) {
        router.replace(`/auth/restaurant/under-review`);
        sessionStorage.clear();
      }
    } catch (error) { }
  };

  const getProfile = async () => {
    try {
      const apiRes = await apis.Profile.getProfile();
      const { data } = apiRes;
      router.push("/auth/restaurant/parent-category");
      setUserInfo((prev: any) => ({
        ...prev,
        ...data,
      }));
      return data;
    } catch (error) { }
  };

  return (
    <>
      <section className="w-full">
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <div className="w-full max-w-xl mx-auto rounded-2xl border border-gray-100 bg-white p-6 sm:p-8 shadow-sm">
              <div className="flex flex-col space-y-6">
                {/* Step 1 */}
                <div className="relative flex items-start gap-4">
                  <div className="flex flex-col items-center">
                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center transition-all ${res === 'complete' ? 'bg-[var(--orange-100)] text-[var(--primary-brand)]' : 'bg-gray-100 text-gray-400'}`}>
                      <Icons.AuthBellIconActive />
                    </div>
                    <div className={`w-0.5 my-2 h-14 ${res === 'complete' ? 'bg-[var(--primary-brand)]/40' : 'bg-gray-200'}`} />
                  </div>
                  <div className="flex-1 pt-1">
                    <div className="flex items-center justify-between">
                      <h3 className="text-base sm:text-lg font-bold text-gray-900">
                        Vendor Information
                      </h3>
                      {res === 'complete' && (
                        <span className="text-xs font-semibold px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-600 border border-emerald-200">
                          Completed
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-gray-500 mt-0.5">
                      Name, location, and contact number
                    </p>
                    <div className="mt-3">
                      {res === "complete" ? (
                        <Button
                          type="button"
                          onClick={getProfile}
                          className="inline-flex items-center gap-2 font-semibold text-xs sm:text-sm bg-[var(--orange-100)] text-[var(--primary-brand)] hover:bg-[var(--primary-brand)] hover:text-white px-4 py-2 rounded-full transition-all duration-200 shadow-sm"
                        >
                          Edit details <Icons.RightArrowYellow />
                        </Button>
                      ) : (
                        <Button
                          type="button"
                          onClick={() => router.push("/auth/restaurant/parent-category")}
                          className="inline-flex items-center gap-2 font-semibold text-xs sm:text-sm bg-[var(--primary-brand)] text-white hover:bg-[var(--primary-brand)]/90 px-5 py-2 rounded-full transition-all duration-200 shadow-sm"
                        >
                          Proceed <Icons.RightArrowYellow />
                        </Button>
                      )}
                    </div>
                  </div>
                </div>

                {/* Step 2 */}
                {showStep2 && (
                  <div className="relative flex items-start gap-4">
                    <div className="flex flex-col items-center">
                      <div className={`w-12 h-12 rounded-xl flex items-center justify-center transition-all ${food === 'complete' ? 'bg-[var(--orange-100)] text-[var(--primary-brand)]' : res === 'complete' ? 'bg-amber-50 text-amber-600 border border-amber-200' : 'bg-gray-100 text-gray-400'}`}>
                        {res === "complete" ? <Icons.MenuIconActive /> : <Icons.MenuIcon />}
                      </div>
                      <div className={`w-0.5 my-2 h-14 ${food === 'complete' ? 'bg-[var(--primary-brand)]/40' : 'bg-gray-200'}`} />
                    </div>
                    <div className="flex-1 pt-1">
                      <div className="flex items-center justify-between">
                        <h3 className={`text-base sm:text-lg font-bold ${res === "complete" ? "text-gray-900" : "text-gray-400"}`}>
                          Menu and operational details
                        </h3>
                        {food === 'complete' && (
                          <span className="text-xs font-semibold px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-600 border border-emerald-200">
                            Completed
                          </span>
                        )}
                      </div>
                      <p className="text-sm text-gray-500 mt-0.5">
                        Menu, dish image, and timings
                      </p>
                      {res === "complete" && (
                        <div className="mt-3">
                          <Button
                            type="button"
                            onClick={() => router.push("/auth/menu/add")}
                            className={`inline-flex items-center gap-2 font-semibold text-xs sm:text-sm px-4 py-2 rounded-full transition-all duration-200 shadow-sm ${food === "complete" ? "bg-[var(--orange-100)] text-[var(--primary-brand)] hover:bg-[var(--primary-brand)] hover:text-white" : "bg-[var(--primary-brand)] text-white hover:bg-[var(--primary-brand)]/90"}`}
                          >
                            {food === "complete" ? "Edit details" : "Proceed"} <Icons.RightArrowYellow />
                          </Button>
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* Step 3 */}
                <div className="relative flex items-start gap-4">
                  <div className="flex flex-col items-center">
                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center transition-all ${bank === 'complete' ? 'bg-[var(--orange-100)] text-[var(--primary-brand)]' : isStep3Active ? 'bg-amber-50 text-amber-600 border border-amber-200' : 'bg-gray-100 text-gray-400'}`}>
                      {isStep3Active ? <Icons.BankDetailsActive /> : <Icons.BankDetails />}
                    </div>
                  </div>
                  <div className="flex-1 pt-1">
                    <div className="flex items-center justify-between">
                      <h3 className={`text-base sm:text-lg font-bold ${isStep3Active ? "text-gray-900" : "text-gray-400"}`}>
                        Documents and Bank Details
                      </h3>
                      {bank === 'complete' && (
                        <span className="text-xs font-semibold px-2.5 py-1 rounded-full bg-emerald-50 text-emerald-600 border border-emerald-200">
                          Completed
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-gray-500 mt-0.5">
                      Bank account and other information
                    </p>
                    {isStep3Active && (
                      <div className="mt-3">
                        <Button
                          type="button"
                          onClick={() => router.push("/auth/restaurant/documents")}
                          className={`inline-flex items-center gap-2 font-semibold text-xs sm:text-sm px-4 py-2 rounded-full transition-all duration-200 shadow-sm ${bank === "complete" ? "bg-[var(--orange-100)] text-[var(--primary-brand)] hover:bg-[var(--primary-brand)] hover:text-white" : "bg-[var(--primary-brand)] text-white hover:bg-[var(--primary-brand)]/90"}`}
                        >
                          {bank === "complete" ? "Edit details" : "Proceed"} <Icons.RightArrowYellow />
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {bank === "complete" && (
                <div className="pt-6 border-t border-gray-100 mt-6">
                  <Button
                    type="button"
                    onClick={handleSubmit}
                    className="w-full h-12 text-base font-bold bg-[var(--primary-brand)] text-white hover:bg-[var(--primary-brand)]/90 rounded-xl transition-all shadow-md"
                  >
                    Submit Registration
                  </Button>
                </div>
              )}
            </div>
          </form>
        </Form>
      </section>
    </>
  );
};

export default function LoginPage() {
  return (
    <AuthLayout
      title="Get started for accepting
Online order’s"
      des="Please keep your menu and the following 
things ready for smooth signup."
      image={authBanner.src}
    >
      <Login />
    </AuthLayout>
  );
}





