'use client'

import Image from "next/image";
import { cn } from "@/lib/utils"
import { Card, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { GUsuarioSchema } from "@/app/(protected)/(administrativo)/_schemas/GUsuarioSchema"
import z from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import GUsuarioLoginService from "@/app/(protected)/(administrativo)/_services/g_usuario/GUsuarioLogin"
import { useForm } from "react-hook-form"
import { useState } from "react"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from "./ui/form"
import LoadingButton from "@/app/_components/loadingButton/LoadingButton";
import { Button } from "./ui/button";

type FormValues = z.infer<typeof GUsuarioSchema>

export function LoginForm({ className, ...props }: React.ComponentProps<"div">) {

  const [loading, setLoading] = useState(false);

  const form = useForm<FormValues>({
    resolver: zodResolver(GUsuarioSchema),
    defaultValues: {
      login: '',
      senha_api: ''
    },
  });

  // onSubmit agora recebe o evento do form através do handleSubmit
  const onSubmit = async (values: FormValues) => {
    setLoading(true);
    try {
      await GUsuarioLoginService(values);
      // aqui você pode redirecionar ou mostrar mensagem de sucesso
    } catch (error) {
      console.error("Erro ao fazer login:", error);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className={cn("flex flex-col gap-6", className)} {...props}>
      <Card className="overflow-hidden p-0">
        <CardContent className="grid p-0 md:grid-cols-2">
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="p-6 md:p-8 gap-3 flex flex-col">

              <div className="flex flex-col items-center text-center mb-6">
                <h1 className="text-2xl font-bold">Bem vindo de volta!</h1>
                <p className="text-muted-foreground text-balance">
                  Entre na sua conta Orius Tecnologia.
                </p>
              </div>

              <FormField
                control={form.control}
                name="login"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Login</FormLabel>
                    <FormControl>
                      <Input type="text" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="senha_api"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Senha</FormLabel>
                    <FormControl>
                      <Input type="password" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {/* Botão de loading */}
              <LoadingButton text="Entrar" textLoading="Aguarde..." type="submit" loading={loading} />

              <div className="after:border-border relative text-center text-sm after:absolute after:inset-0 after:top-1/2 after:z-0 after:flex after:items-center after:border-t my-4">
                <span className="bg-card text-muted-foreground relative z-10 px-2">
                  Ou entre em contato
                </span>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <Button variant="outline" type="button" className="w-full">
                  Chamar no Whatsapp
                </Button>
                <Button variant="outline" type="button" className="w-full">
                  Chamar no Local
                </Button>
              </div>

            </form>
          </Form>

          <div className="bg-brand relative hidden md:flex items-center justify-center">
            <Image
              src="/images/logo-login.svg"
              alt="Logo"
              width={300}
              height={300}
              className="object-contain dark:brightness-[0.2] dark:grayscale"
            />
          </div>
        </CardContent>
      </Card>

      <div className="text-muted-foreground text-center text-xs">
        Ao clicar você concorda com <a href="#">Nossos termos de serviços</a> e <a href="#">Políticas de Privacidade</a>.
      </div>
    </div>
  )
}
