'use client';
import Link from "next/link";
import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import client from "../../Auth";
import { Baseurl, ImageBase } from "../../utils/BaseUrl.utils";
import { Icon } from "@iconify/react";
import PageLoader from "./common-component/PageLoader";
import { setThemeColor, showAlert } from "../../utils/CommonFunction";
import axios from "axios";

const SignInLayerInner = () => {
  const router = useRouter();
  // const params = useParams();
  // const restaurantbranch = params?.restaurantbranch;
  // const RestaruntBranch = restaurantbranch
  const searchParams = useSearchParams()

  const RestaruntBranch = searchParams.get('restaurantbranch')

  const [userData, setUserData] = useState(null);
  const [loading, setLoading] = useState(true)
  const [formData, setFormData] = useState({
    username: "",
    password: ""
  });
  const [fieldErrors, setFieldErrors] = useState({
    username: "",
    password: ""
  });
  const [loginMessage, setLoginMessage] = useState({
    type: "",
    message: ""
  });
  const [showPassword, setShowPassword] = useState(false);

  useEffect(() => {
    const isLogin = JSON.parse(localStorage.getItem("isLogin"));
    if (isLogin) {
      router.push("/admin/dashboard");
    }
  }, [router]);

  useEffect(() => {
    getLoginData();
  }, []);

  useEffect(() => {
    if (loginMessage.message) {
      const timer = setTimeout(() => {
        setLoginMessage({ type: "", message: "" });
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [loginMessage]);

  const getLoginData = async () => {
    setLoading(true)
    try {
      setLoading(true)
      const res = await client.get(`/Dine360%20Restaurant%20Branch%20Link?fields=[%22name%22,%22branch%22,%22restaurant%22,%22logo_url%22,%22title%22,%22slogan%22,%22isemail%22,%22issms%22,%22thankyoumessageinreservation%22,%22colorcode%22]&filters=[[%22name%22,%22=%22,%22${RestaruntBranch}%22]]`);
      setUserData(res.data.data);
      const colorCode = res.data.data[0]?.colorcode
      localStorage.setItem("colorCode", colorCode)
      setThemeColor();
      setLoading(false)
    } catch (error) {
      console.log("error", error);
      setLoading(false)
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value
    }));
    setFieldErrors((prev) => ({
      ...prev,
      [name]: ""
    }));
    setLoginMessage({
      type: "",
      message: ""
    });
  };
  console.log('userData', userData)
  const handleSubmit = async (e) => {
    e.preventDefault();
    const errors = {};
    if (!formData.username.trim()) {
      errors.username = "Email is required";
    }
    if (!formData.password.trim()) {
      errors.password = "Password is required";
    }

    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      return;
    }

    try {

      const Body = {
        restaurantbranch: userData[0].name,
        username: formData.username,
        password: formData.password
      }

      const res = await axios.post(`${Baseurl}/login`, Body)
      console.log("res", res)
      if (res.status == 200) {
        showAlert({ type: "Success", message: res.data.message }, setLoginMessage);
        const isLogin = true;
        const colorCode = userData[0]?.colorcode
        localStorage.setItem("colorCode", colorCode)
        setThemeColor();
        localStorage.setItem("isLogin", JSON.stringify(isLogin));
        localStorage.setItem("restaurantbranch", RestaruntBranch)
        localStorage.setItem("restaruntDetails", JSON.stringify(userData[0]))
        router.push("/admin/dashboard");
      }

    } catch (error) {
      console.log("error", error)
      if (error?.status == 401) {
        showAlert({ type: "Failure", message: error.response.data ? error.response.data.error : "Invalid credentials" }, setLoginMessage);
      } else {
        showAlert({ type: "Failure", message: "error" }, setLoginMessage);
      }
    }
  };

  return (
    <>
      {/* Login success/failure alert */}
      {loginMessage.message && (
        <div
          className={`alert text-center alert-${loginMessage.type === 'Success' ? 'success' : 'danger'} position-fixed top-0 start-50 translate-middle-x mt-3 z-3`}
          role="alert"
          style={{ maxWidth: '600px' }}
        >
          <p className="mb-0 text-sm">{loginMessage.message}</p>
        </div>
      )}
      {
        loading ? (
          <PageLoader />
        ) : (
          <section className='auth d-flex justify-content-center'>
            <div className='auth-right py-32 px-24 d-flex flex-column justify-content-center'>
              <div className="card p-0 p-md-3">
                <div className="card-body">
                  <div className='max-w-464-px mx-auto w-100'>
                    <div className="text-center">
                      <Link href='/' className='mb-20 max-w-290-px d-inline-block'>
                        <img src={`${ImageBase}${userData[0]?.logo_url}`} alt="Restaurant Logo" style={{ maxWidth: "200px" }} />
                      </Link>
                      <h4 className="mb-1 fs-5 fs-md-3">{userData[0]?.title}</h4>
                      <p className='mb-20 text-secondary-light text-lg'>
                        {userData[0]?.slogan}
                      </p>
                    </div>
                    <form onSubmit={handleSubmit}>
                      <div className='position-relative mb-16'>
                        <label className="form-label mb-0">User Name</label>
                        <div className='icon-field'>
                          <span className='icon position-absolute top-50 translate-middle-y'>
                            <Icon icon='mage:user' />
                          </span>
                          <input
                            type='text'
                            name="username"
                            value={formData.username}
                            onChange={handleInputChange}
                            className='form-control h-56-px bg-neutral-50 radius-12 ps-5'
                            placeholder='User Name'
                          />
                        </div>
                        {fieldErrors.username && (
                          <p className="text-danger text-sm mt-1 mb-0">{fieldErrors.username}</p>
                        )}
                      </div>


                      <div className='position-relative mb-20'>
                        <label className="form-label  mb-0">Password</label>
                        <div className='icon-field'>
                          <span className='icon top-50 translate-middle-y'>
                            <Icon icon='solar:lock-password-outline' />
                          </span>
                          <input
                            type={showPassword ? 'text' : 'password'}
                            name="password"
                            value={formData.password}
                            onChange={handleInputChange}
                            className='form-control h-56-px bg-neutral-50 radius-12'
                            id='your-password'
                            placeholder='Password'
                          />
                          <span
                            className={`toggle-password ${showPassword ? 'ri-eye-off-line' : 'ri-eye-line'} cursor-pointer position-absolute end-0 top-50 translate-middle-y me-16 text-secondary-light`}
                            onClick={() => setShowPassword(!showPassword)}
                            data-toggle='#your-password'
                          />
                        </div>
                        {fieldErrors.password && (
                          <p className="text-danger text-sm mt-1  mb-0">{fieldErrors.password}</p>
                        )}
                      </div>

                      <button
                        type='submit'
                        className='btn btn-bg-theme text-sm btn-sm px-12 py-16 w-100 radius-12 mt-1'
                      >
                        Sign In
                      </button>

                      {/* <div className='mt-32 center-border-horizontal text-center'>
                  <span className='bg-base z-1 px-4'>Or sign in with</span>
                </div> */}

                      {/* <div className='mt-32 text-center text-sm'>
                  <p className='mb-0'>
                    Don’t have an account?{" "}
                    <Link href='/sign-up' className='text-primary-600 fw-semibold'>
                      Sign Up
                    </Link>
                  </p>
                </div> */}
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </section>
        )
      }

    </>
  );
};

const SignInLayer = (() => {
  return (
    <Suspense fallback={<PageLoader />}>
      <SignInLayerInner />
    </Suspense>
  )
})

export default SignInLayer;
