

"use client";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { baseUrl } from "@/lib/config";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useTranslation } from "react-i18next";


export function Login() {
      const { t } = useTranslation("login");
  
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });
  const [loading, setLoading] = useState(false);
const router = useRouter();

  // Always keep a predictable shape to avoid rendering issues
  const [error, setError] = useState({ message: "", errors: {} });

  const handleChange = (e) => {
    setFormData((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError({ message: "", errors: {} });

    try {
      const res = await fetch(`${baseUrl}/api/login`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });

      const result = await res.json();
      console.log("hhhhh");
          document.cookie = `sadu_auth_token=${result.access_token}; path=/; max-age=${60 * 60 * 24 * 7}`;

      localStorage.setItem("sadu_auth_token", result.access_token);
      localStorage.setItem("user", JSON.stringify(result.user));
      localStorage.setItem("role", result.role);
      localStorage.setItem("name", result.user?.name);
      localStorage.setItem("email", result.user?.email);
      localStorage.setItem("id", result.user?.id);
      if (!res.ok) {
        setError({
          message: result.message || "Something went wrong",
          errors: result.errors || {},
        });
      } else {
      router.push("/home");
      }
    } catch {
      setError({
        message: "Failed to Login. Please try again.",
        errors: {},
      });
    } finally {
      setLoading(false);
    }
  };
  return (
    <Card className="w-full h-full py-5 md:py-[35px]">
      <CardHeader className="text-center px-4 md:px-6">
        <CardTitle className="text-center text-xl sm:text-[27px]  lg:text-[38px]">
          {t("Login")}
        </CardTitle>
        <CardDescription className="text-[14px] sm:text-[16px]">
         {t("Welcome back! Please log in to access your account.")}
        </CardDescription>
      </CardHeader>
      <CardContent className="px-4 md:px-6">
        <form onSubmit={handleSubmit}>
          <div className="flex flex-col gap-6">
            <div className="grid gap-2">
              <Label
                className="text-[14px] sm:text-[16px] font-medium text-[#262626]"
                htmlFor="email"
              >
                {t("Email")}
              </Label>
              <Input
                id="email"
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                placeholder={t("Enter your Email")}
                required
                className=" h-11 lg:h-[60px] text-[14px] sm:text-[16px]"
              />
            </div>
            <div className="grid gap-2">
              <div className="flex items-center">
                <Label
                  className="text-[14px] sm:text-[16px]"
                  htmlFor="password"
                >
                  {t("Password")}
                </Label>
              </div>
              <Input
                className=" h-11 lg:h-[60px] text-[14px] sm:text-[16px]"
                id="password"
                type="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                placeholder={t("Enter your Password")}
                required
              />
              <Link
                href="/forgot-password"
                className="ml-auto inline-block text-sm underline-offset-4 hover:underline text-[14px] sm:text-[16px]"
              >
                {t("Forgot your password?")}
              </Link>
            </div>
          </div>
          {error.message && (
            <small className="text-red-600">{error.message}</small>
          )}
        </form>
      </CardContent>
      <CardFooter className="flex-col gap-2 px-4 md:px-6">
        <label
          className="flex gap-2 text-[14px] sm:text-[16px]"
          style={{ alignSelf: "start" }}
        >
          <input
            type="checkbox"
            className="w-[18px] h-[18px] md:h-[24px] md:w-[24px]"
          />
         {t("Remember Me")}
        </label>
        <Button
          onClick={handleSubmit}
          disabled={Object.values(formData).some((v) => !v.trim()) || loading}
          className="w-full md:h-11 lg:h-[60px] my-2"
        >
          {loading ? t("Logning up...") :t("Login")}
        </Button>
        <div className="flex gap-[12px] w-full items-center">
          <span className="w-full bg-[#E4E4E7] h-[1px]"></span>
          {t("OR")}
          <span className="w-full bg-[#E4E4E7] h-[1px]"></span>
        </div>
        <Button className="w-full bg-[#F7F7F8] text-black  md:h-11 lg:h-[60px] ">
          <Image
            src="/icons/googleIcons.png"
            width={24}
            height={24}
            alt="google"
          />
          {t("Login with Google")}
        </Button>
        <div className="py-[18px]">
          <div className="flex items-center gap-1 text-[14px] sm:text-[16px]">
            <p>{t("Don’t have an account?")}</p>
            <Link
              className="underline font-medium whitespace-nowrap"
              href="/signup"
            >
              {" "}
              {t("Sign Up")}
            </Link>
            <img
              className="h-[11px] w-[11px]"
              src="/icons/arrow.png"
              alt="arrow"
            />
          </div>
        </div>
      </CardFooter>
    </Card>
  );
}
