"use client";

import Button from "@/components/atoms/buttons/Button";
import ErrorMessageLogin from "@/components/atoms/errors/ErrorMessageLogin";
import { useAuth } from "@/lib/auth-context";
import { SHOP_INFO } from "@/lib/constants";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { FormEvent, useEffect, useState } from "react";

export default function LoginPasswordPage() {
  const router = useRouter();
  const { setUser } = useAuth();

  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({ password: "", general: "" });

  useEffect(() => {
    const storedPhone = sessionStorage.getItem("login_phone");
    const storedRole = sessionStorage.getItem("login_role");
    if (!storedPhone || storedRole !== "manager") {
      router.replace("/login");
      return;
    }
    setPhone(storedPhone);
  }, [router]);

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!password.trim()) {
      setErrors({ password: "Please enter your password", general: "" });
      return;
    }

    setIsLoading(true);
    setErrors({ password: "", general: "" });

    try {
      const res = await fetch("/api/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ phone, password, role: "manager" }),
      });

      if (res.ok) {
        const userData = await res.json();
        setUser(userData);
        localStorage.setItem("coffee-shop-user", JSON.stringify(userData));
        sessionStorage.removeItem("login_phone");
        sessionStorage.removeItem("login_role");
        router.push("/manager");
      } else {
        const STATUS_ERROR_MAP: Record<number, string> = {
          400: "Incorrect login details, please try again",
          401: "Incorrect password",
          403: "Account is locked",
          404: "Account does not exist",
        };
        const msg =
          STATUS_ERROR_MAP[res.status] ??
          (res.status >= 500
            ? "Server error, please try again later"
            : "An error occurred, please try again");
        setErrors({ password: "", general: msg });
      }
    } catch {
      setErrors({
        password: "",
        general: "Unable to connect, please try again",
      });
    } finally {
      setIsLoading(false);
    }
  };

  if (!phone) return null;

  return (
    <div className="bg-background flex min-h-screen items-center justify-center px-4 py-8">
      <div className="w-full max-w-md rounded-2xl bg-white p-8 shadow-lg">
        {/* Logo & Shop Name */}
        <div className="mb-8 flex flex-col items-center">
          <div className="relative mb-4 h-20 w-20">
            <Image
              src={SHOP_INFO.logo}
              alt={SHOP_INFO.name}
              fill
              className="object-contain"
              sizes="80px"
              priority
            />
          </div>
          <h1 className="mb-1 text-2xl font-bold text-(--color-primary-dark)">
            {SHOP_INFO.name}
          </h1>
          <p className="text-sm text-(--color-text-muted)">Manager sign in</p>
        </div>

        {errors.general && <ErrorMessageLogin message={errors.general} />}

        <form onSubmit={handleSubmit} className="space-y-5">
          {/* Phone display */}
          <div className="rounded-lg border border-(--color-border) bg-(--color-background) px-4 py-3 text-sm text-(--color-text-secondary)">
            <i className="fa-solid fa-phone mr-2 text-(--color-text-muted)"></i>
            {phone}
          </div>

          {/* Password Input */}
          <div>
            <label
              htmlFor="password"
              className="mb-2 block text-sm font-medium text-(--color-text-secondary)"
            >
              Password
            </label>
            <div className="relative">
              <i className="fa-solid fa-lock absolute top-1/2 left-4 hidden -translate-y-1/2 text-(--color-text-muted) lg:block"></i>
              <input
                id="password"
                type={showPassword ? "text" : "password"}
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value);
                  setErrors({ password: "", general: "" });
                }}
                placeholder="Enter password"
                disabled={isLoading}
                className={`text-foreground focus:ring-opacity-20 w-full rounded-xl border bg-white px-10 py-3 transition-all duration-150 outline-none placeholder:text-(--color-text-muted) focus:border-(--color-primary) focus:ring-2 focus:ring-(--color-primary) disabled:opacity-60 lg:pl-11 ${errors.password ? "border-red-400" : "border-(--color-border)"}`}
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute top-1/2 right-4 -translate-y-1/2 text-(--color-text-muted) transition-colors hover:text-(--color-primary)"
                aria-label={showPassword ? "Hide password" : "Show password"}
              >
                <i
                  className={`fa-solid ${showPassword ? "fa-eye-slash" : "fa-eye"}`}
                ></i>
              </button>
            </div>
            {errors.password && (
              <ErrorMessageLogin message={errors.password} type="secondary" />
            )}
          </div>

          {/* Buttons */}
          <div className="space-y-3 pt-2">
            <Button
              variant="primaryNoBorder"
              type="submit"
              style="login"
              size="lg"
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                  Processing...
                </>
              ) : (
                "Sign in"
              )}
            </Button>

            <button
              type="button"
              onClick={() => router.push("/login")}
              className="flex w-full items-center justify-center rounded-xl border-2 border-(--color-primary) bg-white py-3 font-semibold text-(--color-primary) transition-all duration-150 hover:bg-(--color-primary) hover:text-white active:scale-98"
            >
              Change phone number
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
