"use client";

import { signIn } from "@/app/(auth-pages)/action";
import {
  defaultSignInValues,
  SignInFormData,
  signInSchema,
} from "@/src/models/auth/sign-in.model";
import { useState, type FormEvent, type ChangeEvent } from "react";

import { z } from "zod";

type SignInFormErrors = Partial<Record<keyof SignInFormData, string>>;

export function useSignInForm() {
  const [formData, setFormData] = useState<SignInFormData>(defaultSignInValues);
  const [errors, setErrors] = useState<SignInFormErrors>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  const validateForm = (): boolean => {
    try {
      signInSchema.parse(formData);
      setErrors({});
      return true;
    } catch (error) {
      if (error instanceof z.ZodError) {
        const formattedErrors: SignInFormErrors = {};
        error.errors.forEach((err) => {
          const path = err.path[0] as keyof SignInFormData;
          formattedErrors[path] = err.message;
        });
        setErrors(formattedErrors);
      }
      return false;
    }
  };

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

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

    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);
    setMessage(null);

    try {
      const result = await signIn(formData);
      if (result.success) {
        setMessage(result.message);
      } else {
        setErrors({
          email: result.message || "Sign in failed. Please try again.",
        });
      }
    } catch (error) {
      console.error("Sign in failed", error);
      setErrors({
        email: "An unexpected error occurred. Please try again.",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return {
    formData,
    errors,
    isSubmitting,
    message,
    setFormData,
    handleChange,
    handleSubmit,
  };
}
