"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useBillboardForm } from "@/contexts/BillboardFormContext";
import { useEffect, useState } from "react";
import useAxios from "@/hooks/useAxios";
import RoundedInput from "@/components/elements/RoundedInput";
import toast from "react-hot-toast";

const validationSchema = Yup.object({
  landline: Yup.string(),
  mobile: Yup.string(),
  telegram: Yup.string(),
  whatsapp: Yup.string(),
  instagram: Yup.string(),
  saveData: Yup.boolean(),
});

interface ContactInfo {
  landline?: string;
  mobile?: string;
  telegram?: string;
  whatsapp?: string;
  instagram?: string;
  saveData?: boolean;
}

interface ApiResponse {
  data: {
    contactInfo: ContactInfo;
  };
}

const Step4 = ({ nextStep }: { nextStep: () => void }) => {
  const { formData, updateForm } = useBillboardForm();
  const { request } = useAxios();
  const [isCheckedOne, setIsCheckedOne] = useState<boolean>(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await request<ApiResponse>(
          "GET",
          "/users/contact-info"
        );
        const contactInfo = response?.data?.contactInfo;

        if (contactInfo) {
          formik.setFieldValue("landline", contactInfo.landline || "");
          formik.setFieldValue("mobile", contactInfo.mobile || "");
          formik.setFieldValue("telegram", contactInfo.telegram || "");
          formik.setFieldValue("whatsapp", contactInfo.whatsapp || "");
          formik.setFieldValue("instagram", contactInfo.instagram || "");
          formik.setFieldValue("saveData", contactInfo.saveData || false);
        }
      } catch (err) {
        console.error("Error fetching contact info:", err);
      }
    };

    fetchData();
  }, []);

  const formik = useFormik({
    initialValues: {
      landline: formData.landline || "",
      mobile: formData.mobile || "",
      telegram: formData.telegram || "",
      whatsapp: formData.whatsapp || "",
      instagram: formData.instagram || "",
      saveData: formData.saveData || false,
    },
    validationSchema,
    onSubmit: (values) => {
      if (
        !formik?.values?.landline &&
        !formik?.values?.mobile &&
        !formik?.values?.telegram &&
        !formik?.values?.whatsapp &&
        !formik?.values?.instagram
      ) {
        toast.error("لطفا حداقل یک راه ارتباطی را وارد کنید.");
      } else {
        updateForm(values);
        nextStep();
      }
    },
  });
  const toggleCheckBox = () => {
    formik.setFieldValue("saveData", !isCheckedOne);
    setIsCheckedOne(!isCheckedOne);
  };
  console.log(formik?.values);

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="flex flex-col gap-2 w-full items-center text-sm"
    >
      <h6 className="font-bold text-xl mb-2">ثبت بیلبورد</h6>

      <RoundedInput
        className={`max-w-full mt-2 ${
          formik.touched.landline && formik.errors.landline
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        type="text"
        maxLength={11}
        placeholder="تلفن ثابت"
        {...formik.getFieldProps("landline")}
      />
      {formik.touched.landline && formik.errors.landline && (
        <p className="text-red-500 text-xs">{formik.errors.landline}</p>
      )}
      <RoundedInput
        className={`max-w-full mt-2 ${
          formik.touched.mobile && formik.errors.mobile
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        type="text"
        maxLength={11}
        placeholder="شماره موبایل"
        {...formik.getFieldProps("mobile")}
      />
      {formik.touched.mobile && formik.errors.mobile && (
        <p className="text-red-500 text-xs">{formik.errors.mobile}</p>
      )}
      <RoundedInput
        className={`max-w-full mt-2 ${
          formik.touched.telegram && formik.errors.telegram
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        type="text"
        placeholder="آیدی تلگرام"
        {...formik.getFieldProps("telegram")}
      />
      {formik.touched.telegram && formik.errors.telegram && (
        <p className="text-red-500 text-xs">{formik.errors.telegram}</p>
      )}
      <RoundedInput
        className={`max-w-full mt-2 ${
          formik.touched.whatsapp && formik.errors.whatsapp
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        type="text"
        placeholder="شماره واتساپ"
        maxLength={11}
        {...formik.getFieldProps("whatsapp")}
      />
      {formik.touched.whatsapp && formik.errors.whatsapp && (
        <p className="text-red-500 text-xs">{formik.errors.whatsapp}</p>
      )}
      <RoundedInput
        className={`max-w-full mt-2 ${
          formik.touched.instagram && formik.errors.instagram
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        type="text"
        placeholder="آیدی اینستاگرام"
        {...formik.getFieldProps("instagram")}
      />
      {formik.touched.instagram && formik.errors.instagram && (
        <p className="text-red-500 text-xs">{formik.errors.instagram}</p>
      )}

      <label className="flex items-center gap-2 justify-start w-full pr-4 mt-4">
        <input
          {...formik.getFieldProps("stateId")}
          className="scale-125"
          type="checkbox"
          onChange={toggleCheckBox}
        />
        <span>اطلاعات من را برای ویترین های بعدی ذخیره کن</span>
      </label>

      <hr />
      <RoundedButton type="submit" className="p-2 px-8 rounded mt-4">
        ثبت و ادامه
      </RoundedButton>
    </form>
  );
};

export default Step4;
