"use client";

import React, { FormEvent, useState } from "react";
import { Input } from "@/shared/ui/input";
import { Button } from "@/shared/ui/button";
import { useTranslations } from "next-intl";
import { contactInfoSubmit } from "@/shared/api/contactSvs";
import formatPhone from "@/shared/lib/formatPhone";
import { toast } from "sonner";

const FreeRecommendationSection = () => {
  const t = useTranslations("");
  const [phone, setPhone] = useState("+998 ");
  const [name, setName] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState("")

  const onContactSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (phone.length === 17 || name.length > 2) {
      setIsLoading(true);
      setIsError("")
      try {
        await contactInfoSubmit(phone, name);
        setName("");
        setPhone("+998 ");
        toast.success("Muvaffaqiyatli yuborildi");
        setIsLoading(false);
      } catch (error) {
        setIsLoading(false);
      }
    } else {
      setIsError("Ma'lumotlarni to'ldiring")
    }
  };
  return (
    <section
      id={"free-recommendation-section"}
      className={
        "relative overflow-hidden section-wrapper bg-[url('/images/recommendation-bg.jpg')] bg-cover bg-no-repeat bg-center"
      }
    >
      <div className={"flex justify-center items-center p-16 max-sm:p-10"}>
        <div
          className={"bg-slate-950/35 w-full h-screen absolute top-0 left-0"}
        />
        <div className="bg-white rounded-xl p-10 relative z-20 w-full max-w-[600px]">
          <h1 className="text-center text-2xl mb-2 font-bold pb-5">
            {t("Bepul maslahat uchun ma'lumotlaringizni kiriting")}
          </h1>
          <form
            action="w-full"
            className={"space-y-5"}
            onSubmit={onContactSubmit}
          >
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={t("Ismingiz")}
            />
            <Input
              value={formatPhone(phone)}
              onChange={(e) => setPhone(formatPhone(e.target.value))}
              placeholder={t("Telefon raqamingiz")}
            />
            <Button className={"w-full"} type="submit" disabled={isLoading}>
              {!isLoading ? t("Yuborish") : t("Yuborilmoqda")}
            </Button>
          </form>
          {isError && <p className="text-center text-red-500 mt-4">{t(isError)}</p>}
        </div>
      </div>
    </section>
  );
};
export default FreeRecommendationSection;
