"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import { useFormik } from "formik";
import * as Yup from "yup";
import LocationSelector from "./step1/LocationSelector";
import { useBillboardForm } from "@/contexts/BillboardFormContext";
import { useEffect, useState } from "react";
import useAxios from "@/hooks/useAxios";
import SelectBox from "@/components/elements/SelectBox";
import { IAdvertisingCategory } from "@/types/types";
import RoundedInput from "@/components/elements/RoundedInput";
import ImageUploader from "./step1/ImageUploader";

const validationSchema = Yup.object({
  stateId: Yup.string().required("انتخاب استان الزامی است"),
  cityId: Yup.string().required("انتخاب شهر الزامی است"),
  categoryId: Yup.string().required("لطفا دسته‌بندی را انتخاب کنید"),
  adsTitle: Yup.string().required("لطفا عنوان وارد کنید"),
  description: Yup.string().required("توضیحات الزامی است"),
  neighbourhood: Yup.string().required("محله الزامی است"),
  address: Yup.string().required("آدرس الزامی است"),
  images: Yup.array()
    .min(1, "حداقل یک عکس انتخاب کنید")
    .max(5, "حداکثر ۵ عکس می‌توانید انتخاب کنید")
    .required("انتخاب تصویر الزامی است"),
  markerCoordinate: Yup.array()
    .of(Yup.number().required())
    .length(2, "انتخاب موقعیت روی نقشه الزامی است")
    .required("انتخاب موقعیت روی نقشه الزامی است"),
});

const Step1 = ({ nextStep }: { nextStep: () => void }) => {
  const { formData, updateForm } = useBillboardForm();
  const [categories, setCategories] = useState<IAdvertisingCategory[]>([]);
  const { request } = useAxios();
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await request<{ categories: IAdvertisingCategory[] }>(
          "GET",
          "/advertising/categories"
        );
        setCategories(response?.categories);
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, []);
console.log(categories);

  const formik = useFormik({
    initialValues: {
      cityId: formData.cityId || "",
      stateId: formData.stateId || "",
      adsTitle: formData.adsTitle || "",
      categoryId: formData.categoryId || "",
      images: formData.images || [],
      address: formData.address || "",
      neighbourhood: formData.neighbourhood || "",
      description: formData.description || "",
      markerCoordinate: formData.markerCoordinate || null,
    },
    validationSchema,
    onSubmit: (values) => {
      updateForm(values);
      nextStep();
    },
  });
  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>
      <SelectBox
        className={`max-w-full bg-secondary-light dark:bg-secondary-dark ${
          formik.touched.categoryId && formik.errors.categoryId
            ? "border-red-500 dark:border-red-500"
            : ""
        }`}
        value={formik.values.categoryId}
        onChange={(e) => formik.setFieldValue("categoryId", e.target.value)}
      >
        <option className="bg-secondary-light dark:bg-secondary-dark" disabled value="">
          دسته بندی
        </option>
        {categories?.map((item: IAdvertisingCategory) => (
          <option className="bg-secondary-light dark:bg-secondary-dark"  key={item._id} value={item.title}>
            {item?.title}
          </option>
        ))}
      </SelectBox>
      {formik.touched.categoryId && formik.errors.categoryId && (
        <p className="text-red-500 text-xs">{formik.errors.categoryId}</p>
      )}
      <hr />
      <RoundedInput
        className={`max-w-full ${
          formik.touched.stateId && formik.errors.stateId
            ? "border-red-500 dark:border-red-500"
            : ""
        }`}
        type="text"
        placeholder="عنوان"
        {...formik.getFieldProps("adsTitle")}
      />
      {formik.touched.adsTitle && formik.errors.adsTitle && (
        <p className="text-red-500 text-xs">{formik.errors.adsTitle}</p>
      )}
      <textarea
        className={`w-full p-4 mt-2 h-24 rounded-3xl border 
    ${
      formik.touched.description && formik.errors.description
        ? "border-red-500 dark:border-red-500"
        : ""
    }
    border-neutral-950 text-neutral-900 dark:text-neutral-50 dark:border-neutral-400 border  font-medium`}
        placeholder="توضیحات"
        {...formik.getFieldProps("description")}
      />
      {formik.touched.description && formik.errors.description && (
        <p className="text-red-500 text-xs">{formik.errors.description}</p>
      )}

      <hr className="w-full my-2" />
      <LocationSelector formik={formik} />
      <ImageUploader formik={formik} />
      {formik.touched.images && formik.errors.images && (
        <p className="text-red-500 text-xs">{formik.errors.images}</p>
      )}
      <RoundedButton type="submit" className="p-2 px-8 rounded mt-4">
        ثبت و ادامه
      </RoundedButton>
    </form>
  );
};

export default Step1;
