
"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { motion } from "motion/react";
import { Eye, EyeOff, User } from "lucide-react";
import signupImg from "../../../../public/assets/signup/signup.jpg";
import { loginUser } from "@/lib/api/auth";
import Link from "next/link";

type LoginResponse = {
  message?: string;
  user?: {
    id: string;
    name: string;
    email: string;
    mobile: string;
    role: string;
    status: string;
  };
  accessToken?: string;
};

export default function Signin() {
  const router = useRouter();

  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [formData, setFormData] = useState({
    emailOrMobile: "",
    password: "",
  });

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    setFormData((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  };

  // const handleSubmit = async (
  //   e: React.FormEvent<HTMLFormElement>
  // ) => {
  //   e.preventDefault();

  //   if (loading) return;

  //   setLoading(true);
  //   setError("");

  //   try {
  //    const apiUrl = process.env.NEXT_PUBLIC_API_URL;

  //     if (!apiUrl) {
  //       throw new Error("API URL is not configured.");
  //     }

  //     const response = await fetch(
  //       `${apiUrl.replace(/\/+$/, "")}/auth/login`,
  //       {
  //         method: "POST",
  //         headers: {
  //           "Content-Type": "application/json",
  //         },
  //         credentials: "include",
  //         body: JSON.stringify({
  //           emailOrMobile: formData.emailOrMobile.trim(),
  //           password: formData.password,
  //         }),
  //       }
  //     );

  //     const data: LoginResponse & { message?: string | string[] } =
  //       await response.json().catch(() => ({}));

  //     if (!response.ok) {
  //       const message = Array.isArray(data.message)
  //         ? data.message.join(", ")
  //         : data.message;

  //       throw new Error(
  //         message || `Login failed (${response.status}).`
  //       );
  //     }

  //     if (!data.user) {
  //       throw new Error(
  //         "Login response did not contain user information."
  //       );
  //     }

  //     // Backend sets the HttpOnly authentication cookie.
  //     // Never try to read that cookie using document.cookie.
  //     setFormData({
  //       emailOrMobile: "",
  //       password: "",
  //     });

  //     // Redirect after successful authentication.
  //     router.replace("/dashboard");
  //     router.refresh();
  //   } catch (err) {
  //     setError(
  //       err instanceof Error
  //         ? err.message
  //         : "Unable to connect to the server."
  //     );
  //   } finally {
  //     setLoading(false);
  //   }
  // };


  
const handleSubmit = async (
  e: React.FormEvent<HTMLFormElement>,
) => {
  e.preventDefault();

  if (loading) return;

  const emailOrMobile = formData.emailOrMobile.trim();
  const password = formData.password;

  if (!emailOrMobile || !password) {
    setError("Please enter your email/mobile and password.");
    return;
  }

  setLoading(true);
  setError("");

  try {
    const result = await loginUser({
      identifier: emailOrMobile,
      password,
    });

    // Backend response contains authenticated user information.
    const user = result.user!;

    // Clear sensitive form values after successful login.
    setFormData({
      emailOrMobile: "",
      password: "",
    });

    // HttpOnly cookie must be handled by the backend/browser.
    // Do not save access tokens in localStorage here.

    console.log("Logged in user:", {
      id: user.id,
      name: user.name,
      email: user.email,
      role: user.role,
      status: user.status,
    });

    router.replace("/dashboard");
    router.refresh();
  } catch (err: unknown) {
    setError(
      err instanceof Error
        ? err.message
        : "Unable to connect to the server.",
    );
  } finally {
    setLoading(false);
  }
};

  return (
    <div className="min-h-screen w-full lg:flex">
      {/* Left image */}
      <div className="hidden flex-1 lg:block">
        <img
          className="h-full w-full object-cover"
          src={signupImg.src}
          alt="Sign in"
        />
      </div>

      {/* Sign in form */}
      <motion.div
        className="flex w-full items-center justify-center bg-white px-6 sm:px-12 lg:w-1/2"
        initial={{ x: 0, opacity: 0 }}
        animate={{ x: 0, opacity: 1 }}
        transition={{ duration: 0.8, delay: 0.2 }}
      >
        <div className="mb-5 mt-16 w-full max-w-md lg:mt-[136px]">
          <motion.div
            className="mx-auto mb-6 flex h-12 w-12 items-center justify-center rounded-full bg-gray-200"
            whileHover={{ scale: 1.1, rotate: 360 }}
            transition={{ duration: 0.5 }}
          >
            <User className="h-6 w-6 text-gray-600" />
          </motion.div>

          <motion.h1
            className="mb-2 text-center text-4xl"
            initial={{ y: -20, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            transition={{ delay: 0.4 }}
          >
            Sign In Account
          </motion.h1>

          <p className="mb-8 text-center text-gray-500">
            Enter your details to sign in
          </p>

          <form onSubmit={handleSubmit} className="space-y-5">
            {/* Error message */}
            {error && (
              <div
                role="alert"
                className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
              >
                {error}
              </div>
            )}

            {/* Email or mobile */}
            <motion.div
              initial={{ x: -20, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              transition={{ delay: 0.6 }}
            >
              <label
                htmlFor="emailOrMobile"
                className="mb-2 block text-sm"
              >
                Email or Mobile Number
              </label>

              <input
                id="emailOrMobile"
                type="text"
                name="emailOrMobile"
                autoComplete="username"
                value={formData.emailOrMobile}
                onChange={handleInputChange}
                placeholder="Enter email or mobile number"
                className="w-full rounded-full border-none bg-gray-100 px-4 py-3 outline-none transition-all focus:ring-2 focus:ring-gray-300"
                required
                disabled={loading}
              />
            </motion.div>

            {/* Password */}
            <motion.div
              initial={{ x: -20, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              transition={{ delay: 0.9 }}
            >
              <label
                htmlFor="password"
                className="mb-2 block text-sm"
              >
                Password
              </label>

              <div className="relative">
                <input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  name="password"
                  autoComplete="current-password"
                  value={formData.password}
                  onChange={handleInputChange}
                  placeholder="Enter your password"
                  className="w-full rounded-full border-none bg-gray-100 px-4 py-3 pr-12 outline-none transition-all focus:ring-2 focus:ring-gray-300"
                  required
                  disabled={loading}
                />

                <button
                  type="button"
                  onClick={() =>
                    setShowPassword((prev) => !prev)
                  }
                  aria-label={
                    showPassword ? "Hide password" : "Show password"
                  }
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 transition-colors hover:text-gray-600"
                >
                  {showPassword ? (
                    <EyeOff size={20} />
                  ) : (
                    <Eye size={20} />
                  )}
                </button>
              </div>
              <div className="text-right mt-2">
                 <Link href={'/forgot-password'} className="text-sm text-green-700 cursor-pointer underline">Forgot Password</Link>
              </div>
            </motion.div>

            {/* Submit */}
            <motion.button
              type="submit"
              disabled={loading}
              className="w-full cursor-pointer rounded-full bg-background py-3 text-white transition-all hover:bg-bghover disabled:cursor-not-allowed disabled:opacity-60"
              whileHover={loading ? undefined : { scale: 1.02 }}
              whileTap={loading ? undefined : { scale: 0.98 }}
              initial={{ y: 20, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              transition={{ delay: 1 }}
            >
              {loading ? "Signing In..." : "Sign In"}
            </motion.button>

            {/* Divider */}
            <div className="my-6 flex items-center gap-4">
              <div className="h-px flex-1 bg-gray-300" />
              <span className="text-sm text-gray-400">Or</span>
              <div className="h-px flex-1 bg-gray-300" />
            </div>

            {/* Google button - UI only */}
            <motion.div
              className="flex gap-3"
              initial={{ y: 20, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              transition={{ delay: 1.1 }}
            >
              <motion.button
                type="button"
                onClick={() =>
                  setError(
                    "Google sign-in has not been configured yet."
                  )
                }
                className="flex flex-1 items-center justify-center gap-2 rounded-full bg-gray-100 py-3 transition-all hover:bg-gray-200"
                whileHover={{ scale: 1.02 }}
                whileTap={{ scale: 0.98 }}
              >
                <svg
                  width="20"
                  height="20"
                  viewBox="0 0 20 20"
                  aria-hidden="true"
                >
                  <path
                    d="M19.6 10.23c0-.82-.1-1.42-.25-2.05H10v3.72h5.5c-.15.96-.74 2.31-2.04 3.22v2.45h3.16c1.89-1.73 2.98-4.3 2.98-7.34z"
                    fill="#4285F4"
                  />
                  <path
                    d="M13.46 15.13c-.83.59-1.96 1-3.46 1-2.64 0-4.88-1.74-5.68-4.15H1.07v2.52C2.72 17.75 6.09 20 10 20c2.7 0 4.96-.89 6.62-2.42l-3.16-2.45z"
                    fill="#34A853"
                  />
                  <path
                    d="M3.99 10c0-.69.12-1.35.32-1.97V5.51H1.07A9.973 9.973 0 000 10c0 1.61.39 3.14 1.07 4.49l3.24-2.52c-.2-.62-.32-1.28-.32-1.97z"
                    fill="#FBBC05"
                  />
                  <path
                    d="M10 3.88c1.88 0 3.13.81 3.85 1.48l2.84-2.76C14.96.99 12.7 0 10 0 6.09 0 2.72 2.25 1.07 5.51l3.24 2.52C5.12 5.62 7.36 3.88 10 3.88z"
                    fill="#EA4335"
                  />
                </svg>
                Google
              </motion.button>
            </motion.div>

            <motion.p
              className="mt-6 text-center text-sm text-gray-600"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 1.2 }}
            >
              Don&apos;t have an account?{" "}
              <a href="/signup" className="hover:underline">
                Create Account
              </a>
            </motion.p>
          </form>
        </div>
      </motion.div>
    </div>
  );
}
