"use client";
import { getToken } from "@/actions/cookies";
import postData from "@/api/post-data";
import { Input } from "@/components/ui/input";
import { toastError } from "@/services/custom-toast";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
import SubmitButton from "../shared/SubmitButton";

export default function LinkInput() {
  const t = useTranslations("affiliate");
  const e = useTranslations("form-errors");
  const locale = useLocale();
  const [link, setLink] = useState("");
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm({
    defaultValues: {
      link: "",
    },
  });
  return (
    <form
      onSubmit={handleSubmit(async (values) => {
        const formData = new FormData();
        formData.append("link", values.link);
        const { error, message, data } = await postData({
          endPoint: "/user/affiliate/generate",
          locale,
          body: formData,
        });
        if (error) {
          toastError(message);
          return;
        }
        setLink(data ?? "not found link");
        reset();
      })}
      className="flex flex-col items-start lg:flex-row gap-6 mt-4 ms-4"
    >
      <div className="space-y-4 w-1/3">
        <div>
          <Input
            {...register("link", { required: e("required") })}
            type="text"
            placeholder={t("link")}
          />
          {errors.link && (
            <span className="text-red-500 text-xs">{errors.link.message}</span>
          )}
        </div>
        <SubmitButton
          className="max-w-32 bg-main hover:bg-main/90"
          loading={isSubmitting}
          text={t("choose-link")}
        />
      </div>
      {link && <p className="text-center bg-main/5 p-3">{link}</p>}
    </form>
  );
}
