"use client";

import React, { useState } from "react";
import { Service } from "@/types/types";
import ServiceItem from "@/components/main/Services/ServiceItem";
import AddServiceModal from "@/components/main/Services/AddServiceModal";
import AuthUserDetails from "@/components/auth/AuthUserDetails";
import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import { dataURLtoBlob } from "@/helpers/helpers";
import { useRouter } from "next/navigation";

const ServicesPage: React.FC = () => {
  const [services, setServices] = useState<Service[]>([]);
  const [isModalOpen, setModalOpen] = useState(false);
  const { request, loading } = useAxios();

  const [expertise] = useState<string>(
    typeof window !== "undefined" ? localStorage.getItem("expertise") || "" : ""
  );

  // افزودن خدمت جدید
  const handleAddService = (newService: Service) => {
    setServices((prev) => [...prev, newService]);
  };

  // حذف خدمت
  const handleDeleteService = (id: string) => {
    setServices((prev) => prev.filter((service) => service.id !== id));
  };

  const router = useRouter();

  const handleSubmit = async () => {
    if (services.length === 0) {
      toast.error("لطفاً حداقل یک خدمت وارد کنید.");
      return;
    }

    const formData = new FormData();
    formData.append("services", JSON.stringify(services));

    // اضافه کردن تصاویر خدمات
    services.forEach(({ id, image }) => {
      if (image) {
        formData.append(
          `serviceImages[${id}]`,
          dataURLtoBlob(image),
          `service-${id}.jpg`
        );
      }
    });

    try {
      await request("post", "/verify/services", formData, {
        headers: { "Content-Type": "multipart/form-data" },
      });
      toast.success("خدمات با موفقیت ثبت شدند!");
      setServices([]); // ریست لیست پس از ثبت

      if (expertise === "مدل") {
        router.push("/verify/sizes");
      } else {
        router.push("/verify/public-relations");
      }
    } catch (error) {
      console.log(error);
      toast.error("خطا در ثبت خدمات!");
    }
  };

  const Reject = () => {
    if (expertise === "مدل") {
      router.push("/verify/sizes");
    } else {
      router.push("/verify/public-relations");
    }
  };

  return (
    <AuthPageLayout>
      <AuthPageContent className="w-full">
        <span className="text-xl font-bold">خدمات</span>

        <div className="mt-5 w-full max-w-md">
          <AuthUserDetails />
        </div>

        <div className="gap-4 min-h-[384px] max-h-96 overflow-y-auto w-full mt-4">
          {services.map((service) => (
            <ServiceItem
              onDelete={handleDeleteService}
              key={service.id}
              service={service}
            />
          ))}
        </div>

        {isModalOpen && (
          <AddServiceModal
            onClose={() => setModalOpen(false)}
            onAdd={handleAddService}
            isModalOpen={isModalOpen}
          />
        )}
      </AuthPageContent>

      <AuthFormFooter onSkip={Reject}>
        <div className="flex gap-4">
          <AuthNextButton
            onClick={handleSubmit}
            loading={loading}
            disabled={loading}
            className="w-32"
          >
            ثبت و ادامه
          </AuthNextButton>

          <AuthNextButton
            onClick={() => setModalOpen(true)}
            className="!text-[#0066FF] !border-[#0066FF] w-32"
          >
            افزودن
          </AuthNextButton>
        </div>
      </AuthFormFooter>
    </AuthPageLayout>
  );
};

export default ServicesPage;
