"use client";
import { yupResolver } from "@hookform/resolvers/yup";
import { useRouter } from "next/navigation"; // Import the useRouter hook
import { useState } from "react";
import { schema } from "./schema";
import { SubmitHandler, useForm } from "react-hook-form";
import InputField from "../components/InputField";
import Button from "../components/PrimaryButton";
import { NextResponse } from "next/server";


interface LoginFormInputs {
  username: string;
  password: string;
}



export default function LoginForm() {
  const [error, setError] = useState("");

  const router = useRouter(); // Initialize the router

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<LoginFormInputs>({
    resolver: yupResolver(schema),
  });

  const onSubmit: SubmitHandler<LoginFormInputs> = async (data) => {
    console.log("Form Data:", data);
    try {
      const response = await fetch("http://localhost:3000/api/auth/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
        credentials: "include", // Ensures cookies are included with the request
      });
  
      if (response.ok) {
        const result = await response.json();
        console.log("Login Successful:", result);
  
        // Redirect to dashboard if login is successful
        if (result.success) {
          router.push("/dashboard");
        } else {
          console.error("Login Failed:", result.message);
        }
      } else {
        setError('Something went wrong!')
      }
    } catch (error) {
      console.error("Error while logging in:", error);
    }
  };


  return (
    <div className="fade-in  flex items-center justify-center min-h-screen bg-gray-100">
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="bg-white p-8 shadow-lg rounded-lg w-full max-w-md"
      >
        <h2 className="text-2xl font-bold mb-6 text-center text-gray-700">
          Login
        </h2>

        {error && (
          <div className="bg-red-100 text-red-700 p-2 ps-3 rounded mb-4 text-sm">
            {error}
          </div>
        )}

        <div className="mb-4">
          <InputField
            label="Username"
            placeholder="Enter your username"
            name="username"
            register={register}
            error={errors.username?.message}
          />
        </div>

        <div className="mb-6">



          <InputField
            label="Password"
            placeholder="Enter your Password"
            name="password"
            register={register}
            error={errors.password?.message}
          />
        </div>

        <Button type="submit" disabled={isSubmitting} isLoading={isSubmitting}>
          Submit
        </Button>

        <p className="mt-4 text-center text-sm text-gray-500">
          Don't have an account?{" "}
          <a href="#" className="text-blue-600 hover:underline">
            Sign up
          </a>
        </p>
      </form>
    </div>
  );
}
