"use client";

import React, { useEffect, useState } from "react";
import { Service, User } from "@/types/types";
import ServiceItem from "@/components/main/Services/ServiceItem";
import AddServiceModal from "@/components/main/Services/AddServiceModal";
import AuthUserDetails from "@/components/auth/AuthUserDetails";
import Container from "@/components/elements/Container";
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 router = useRouter();
  const { request, loading } = useAxios();
  const [services, setServices] = useState<Service[]>([]);
  const [isModalOpen, setModalOpen] = useState(false);
  const [user, setUser] = useState<User>();

  const fetchUser = async () => {
    try {
      const response = await request<{ user: User }>(
        "GET",
        "/profile?services=1"
      );
      setUser(response?.user);
    } catch (error) {
      console.error("Failed to fetch user:", error);
    }
  };
  useEffect(() => {
    fetchUser();
  }, []);

  useEffect(() => {
    setServices(user?.services || []);
  }, [user]);
  const handleAddService = (newService: Service) => {
    setServices([...services, newService]);
  };
  const handleDeleteService = (id: string) => {
    setServices(
      services.filter((service) => service.id !== id && service._id !== id)
    );
  };

  const handleSubmit = async () => {
    if (services.length === 0) {
      toast.error("لطفاً حداقل یک خدمت وارد کنید.");
      return;
    }
    const formData = new FormData();
    formData.append("services", JSON.stringify(services));
    // اضافه کردن تصاویر خدمات به فرم داده
    services.forEach((service) => {
      if (service.image) {
        const blob =
          !service.image.startsWith("/services/") &&
          dataURLtoBlob(service.image);
        if (
          typeof service.image === "string" &&
          service.image.startsWith("/services/")
        ) {
          formData.append(
            `existingServiceImages[${service.id}]`,
            service.image
          );
        } else if (service.image && blob) {
          formData.append(
            `serviceImages[${service.id}]`,
            blob,
            `service-${service.id}.jpg`
          );
        }
      }
    });
    try {
      await request("POST", "/verify/services", formData, {
        headers: {
          Accept: "application/json",
          "Content-Type": "multipart/form-data",
        },
      });
      router.push("/settings/edit");
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <Container>
      <div className="p-4 flex flex-col items-center h-screen justify-center">
        <span className="text-xl font-bold text-foreground">خدمات</span>

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

        <div className="gap-4 min-h-96">
          {services.map((service) => (
            <ServiceItem
              onDelete={() =>
                handleDeleteService(service?._id ? service?._id : service?.id)
              }
              key={service.id || service._id}
              service={service}
            />
          ))}
        </div>
        <div className="flex gap-4">
          <AuthNextButton
            onClick={handleSubmit}
            loading={loading} disabled={loading}
            className="mb-4 w-32"
          >
            ویرایش
          </AuthNextButton>
          <AuthNextButton
            onClick={() => setModalOpen(true)}
            className="mb-4 !text-[#0066FF] !border-[#0066FF] w-32"
          >
            افزودن
          </AuthNextButton>
        </div>
        {isModalOpen && (
          <AddServiceModal
            onClose={() => setModalOpen(false)}
            onAdd={handleAddService}
            isModalOpen={isModalOpen}
          />
        )}
      </div>
    </Container>
  );
};

export default ServicesPage;
