"use client";

import React, { useEffect } from "react";
import * as z from "zod";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";

import { LoginSchema } from "@/lib/db/schemas";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { PasswordInput } from "@/components/ui/PasswordInput";
import { CardWrapper } from "@/components/auth/CardWrapper";
import { Button } from "@/components/ui/button";
import { FormError } from "@/components/ui/FormError";
import { login } from "@/actions/login";
import { useSearchParams } from "next/navigation";
import { useAction } from "@/hooks/useAction";

const LoginForm = () => {
  const { execute, isLoading, validationErrors, error } = useAction(login);
  const searchParams = useSearchParams();
  const urlError =
    searchParams.get("error") === "OAuthAccountNotLinked"
      ? "Bitte verknüpfen Sie Ihr Konto mit Google."
      : "";
  const callbackUrl = searchParams.get("callbackUrl");

  const form = useForm<z.infer<typeof LoginSchema>>({
    resolver: zodResolver(LoginSchema),
    defaultValues: {
      email: "",
      password: "",
      callbackUrl: callbackUrl || "",
    },
  });

  // Sync server-side validation errors
  useEffect(() => {
    if (validationErrors) {
      Object.keys(validationErrors).forEach((key) => {
        form.setError(key as any, {
          type: "server",
          message: validationErrors[key][0],
        });
      });
    }
  }, [validationErrors, form]);

  const onSubmit = async (values: z.infer<typeof LoginSchema>) => {
    await execute(values);
    // Redirection is handled by the server action (signIn) via NEXT_REDIRECT
  };

  return (
    <CardWrapper
      headerLabel="Willkommen zurück!"
      backButtonLabel="Neues Kundenkonto anlegen"
      backButtonHref="/auth/register"
      showSocial
    >
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <input type="hidden" {...form.register("callbackUrl")} />
          <div className="space-y-4">
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>E-Mail</FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      disabled={isLoading}
                      placeholder="E-Mail-Adresse"
                      type="email"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Passwort</FormLabel>
                  <FormControl>
                    <PasswordInput
                      {...field}
                      disabled={isLoading}
                      placeholder="******"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
          {/* Global errors (like urlError or general action error) */}
          {(error || urlError) && <FormError message={error || urlError} />}
          <Button disabled={isLoading} type="submit" className="w-full">
            {isLoading ? "Wird angemeldet..." : "Login"}
          </Button>
        </form>
      </Form>
    </CardWrapper>
  );
};

export default LoginForm;
