"use client";

import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { signIn } from "next-auth/react";

import { Card, Typography, Alert, Layout } from "antd";
import Link from "next/link";
import { copyright, frontEndUrl } from "@/app/utils/variables";
import { useSiteContext } from "@/app/Context/SiteContext";
import InputItem from "../FormItems";
import { AlertMessage } from "../AlertMessage";
import { errorMessage } from "@/app/utils/alertMessages";

/* ===============================
   SET BRAND COLOR COOKIE
================================ */
const setBrandColorCookie = (color) => {
  if (!color) return;

  document.cookie = `brand_color=${encodeURIComponent(
    color,
  )}; path=/; max-age=${60 * 60 * 24 * 30}; SameSite=Lax`;
};

export const Login = () => {
  const { brandData, brandColor, activeTheme } = useSiteContext();
  const { Footer } = Layout;
  const { Title } = Typography;

  const router = useRouter();
  const searchParams = useSearchParams();

  const primaryColor = brandColor || brandData?.primary_color || "#eee";

  const [form, setForm] = useState({
    username: "",
    password: "",
    rememberMe: false,
  });

  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  /* ===============================
     HANDLE INPUT CHANGE
  ================================ */
  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;

    setForm((prev) => ({
      ...prev,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

  /* ===============================
     HANDLE LOGIN SUBMIT
  ================================ */
const handleSubmit = async (e) => {
  e.preventDefault();

  //  Simple client validation
  if (!form.username.trim() || !form.password.trim()) {
    errorMessage("Please enter your email/username and password.");
    return;
  }

  setLoading(true);
  setError("");

  const res = await signIn("credentials", {
    redirect: false,
    username: form.username,
    password: form.password,
    rememberMe: form.rememberMe ? "true" : "false",
    callbackUrl: searchParams.get("callbackUrl") || "/dashboard",
  });

  setLoading(false);

  if (res?.error) {
    errorMessage("Invalid email, username, or password.");
    return;
  }

  if (res?.ok) {
    setBrandColorCookie(brandData?.primary_color);
    router.push(res.url || "/dashboard");
  }
};


  return (
    <form onSubmit={handleSubmit} className="block w-full">
      <div className="grid  gap-[30px]  h-[70vh] pb-10">
        <div className="flex flex-col justify-center gap-[30px]">


          {/* ================= ERROR ================= */}
          {error && (
            <div className="mt-3">
              {/* <Alert message={error} type="error" showIcon /> */}
              <AlertMessage
             size="small"
               type="error"
  message={error ? 'Incorrect email, username, or password.' : ''}
              />
            </div>
          )}

          {/* ================= HEADER ================= */}
          <div className="text-start  hidden xl:block">
            <span className="font-normal md:text-[22px] text-[24px] block mb-[4px]">
              Login to your account
            </span>
            {/* <span className="text-[16px] md:text-[14px] text-gray-500 block m-0">
              Please enter your details to access your account.
            </span> */}
          </div>

          {/* ================= FORM ================= */}
          <div className="grid gap-[24px]">
            <InputItem
              type="textspecial"
              name="username"
              value={form.username}
              onChange={handleChange}
              placeholder="Email or username"
            />

            <InputItem
              type="password"
              name="password"
              value={form.password}
              onChange={handleChange}
              placeholder="Password"
            />

            {/* ================= SUBMIT ================= */}
            <div className="flex justify-start w-full">
              <InputItem
                type="button"
                title={loading ? "Sign in..." : "Sign In"}
                onClick={handleSubmit}
                disabled={loading}
                btnColor={primaryColor}
                className="w-full h-10 rounded text-white font-bold !border-none"
                btnvariant="solid"
              />
            </div>

            <div className="flex items-center">
              <InputItem
                type="checkbox"
                name="rememberMe"
                checked={form.rememberMe}
                onChange={handleChange}
                className="!text-[16px] w-full"
                title="Remember me"
              />

              <Link
                href="/auth/forgot-password"
                style={{ color: activeTheme?.primary, textDecoration: "none" }}
                className="text-right block !text-[14px] w-full"
              >
                Forgot password?
              </Link>
            </div>
          </div>

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