"use client";

import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import AuthNextButton from "@/components/auth/AuthNextButton";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import ServiceItem from "@/components/main/Services/ServiceItem";
import AddServiceModal from "@/components/main/Services/AddServiceModal";
import useAxios from "@/hooks/useAxios";
import { useBookingWizardId } from "@/hooks/useBookingWizardId";
import { Service, User } from "@/types/types";
import { dataURLtoBlob } from "@/helpers/helpers";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

function BookingServicesPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const configId = useBookingWizardId();

  const [services, setServices] = useState<Service[] | null>(null);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [isAddModalOpen, setAddModalOpen] = useState(false);
  const [adding, setAdding] = useState(false);

  const fetchServices = () =>
    request<{ user: User }>("GET", "/profile?services=1").then((res) => {
      setServices(res?.user?.services || []);
    });

  useEffect(() => {
    fetchServices();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!configId) return;
    request<{ config: { services?: { serviceId: string }[] } }>(
      "GET",
      `/bookings/${configId}`
    ).then((res) => {
      const ids = (res?.config?.services || []).map((s) => s.serviceId);
      if (ids.length) setSelectedIds(new Set(ids));
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [configId]);

  const toggle = (id: string) => {
    setSelectedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const handleAddService = async (newService: Service) => {
    if (!services) return;
    setAdding(true);
    const previousIds = new Set(
      services.map((s) => s.id || s._id || "").filter(Boolean)
    );
    const nextServices = [...services, newService];

    try {
      const formData = new FormData();
      formData.append("services", JSON.stringify(nextServices));
      nextServices.forEach((service) => {
        if (!service.image) return;
        if (service.image.startsWith("/services/")) {
          formData.append(`existingServiceImages[${service.id}]`, service.image);
        } else {
          const blob = dataURLtoBlob(service.image);
          formData.append(`serviceImages[${service.id}]`, blob, `service-${service.id}.jpg`);
        }
      });

      await request("POST", "/verify/services", formData, {
        headers: { Accept: "application/json", "Content-Type": "multipart/form-data" },
      });

      const res = await request<{ user: User }>("GET", "/profile?services=1");
      const refreshed = res?.user?.services || [];
      setServices(refreshed);
      setAddModalOpen(false);

      const addedService = refreshed.find(
        (s) => !previousIds.has(s.id || s._id || "")
      );
      if (addedService) {
        const addedId = addedService.id || addedService._id || "";
        if (addedId) toggle(addedId);
      }
      toast.success(t("settings.edit.save"));
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    } finally {
      setAdding(false);
    }
  };

  const handleSubmit = async () => {
    if (!configId || selectedIds.size === 0) return;
    try {
      await request("PATCH", `/bookings/${configId}/services`, {
        serviceIds: Array.from(selectedIds),
      });
      router.push("/settings/booking/new/schedule");
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <div className="flex w-full flex-1 flex-col items-center pb-28">
          <AuthPageContent>
            <div className="mb-4 flex w-full max-w-sm items-center justify-between">
              <span className="text-xl font-bold">
                {t("booking.servicesTitle")}
              </span>
              <button
                type="button"
                onClick={() => setAddModalOpen(true)}
                className="text-sm font-semibold text-[#0095f6]"
              >
                + {t("settings.edit.add")}
              </button>
            </div>

            {services === null ? (
              <p className="py-8 text-sm text-neutral-500">
                {t("common.loading")}
              </p>
            ) : services.length === 0 ? (
              <div className="flex flex-col items-center gap-3 py-8 text-center text-sm text-neutral-500">
                <p>{t("booking.noServicesYet")}</p>
                <Link
                  href="/settings/edit/services"
                  className="font-semibold text-[#0095f6]"
                >
                  {t("booking.goAddServices")}
                </Link>
              </div>
            ) : (
              <div className="flex w-full max-w-sm flex-col">
                {services.map((service) => {
                  const id = service.id || service._id || "";
                  const selected = selectedIds.has(id);
                  return (
                    <div
                      key={id}
                      role="button"
                      tabIndex={0}
                      onClick={() => toggle(id)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" || e.key === " ") toggle(id);
                      }}
                      className={`relative w-full cursor-pointer rounded-2xl ${
                        selected ? "bg-[#0095f6]/10" : ""
                      }`}
                    >
                      <span
                        className={`absolute -right-1 top-1/2 z-10 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full border-2 ${
                          selected
                            ? "border-[#0095f6] bg-[#0095f6]"
                            : "border-neutral-300 bg-white dark:border-neutral-600 dark:bg-neutral-900"
                        }`}
                      >
                        {selected && (
                          <span className="h-2 w-2 rounded-full bg-white" />
                        )}
                      </span>
                      <ServiceItem service={service} />
                    </div>
                  );
                })}
              </div>
            )}
          </AuthPageContent>
          <AuthFormFooter className="fixed inset-x-0 bottom-[calc(5.5rem+env(safe-area-inset-bottom))] z-20 mx-auto mt-0 w-full max-w-xl bg-background/95 px-4 py-3 backdrop-blur-sm">
            <AuthNextButton
              type="button"
              loading={loading}
              disabled={loading || !configId || selectedIds.size === 0}
              onClick={handleSubmit}
            >
              {t("shops.saveAndContinue")}
            </AuthNextButton>
          </AuthFormFooter>
        </div>
        {isAddModalOpen && (
          <AddServiceModal
            isModalOpen={isAddModalOpen}
            onClose={() => !adding && setAddModalOpen(false)}
            onAdd={handleAddService}
          />
        )}
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default BookingServicesPage;
