"use client";
import ApiLoader from "@/components/layouts/api-loader";
import ErrorFallback from "@/components/layouts/error-fallback";
import Hero from "@/components/layouts/hero";
import ServiceCard from "@/components/layouts/service-card";
import { useServiceById } from "@/queries/use-service-by-id";
import { useServices } from "@/queries/use-services";
import Image from "next/image";
import Link from "next/link";
import { useParams } from "next/navigation";
import React from "react";

const Page = () => {
  const { id } = useParams();
  const {
    data: services,
    isLoading: isServicesLoading,
    isError: isServicesError,
  } = useServices();

  const {
    data: selectedService,
    isLoading: isSelectedServiceLoading,
    isError: isSelectedServiceError,
  } = useServiceById(id! as string);

  const breadCrumbPaths = [
    { text: "Home", routeTo: "/" },
    { text: "Services", routeTo: "/services" },
    { text: `${selectedService?.name}`, routeTo: `${selectedService?.slug}` },
  ];

  const otherServices = services?.filter(
    (service) => service.id.toString() == (id as string),
  );

  if (isServicesError || isSelectedServiceError) {
    return <ErrorFallback />;
  }

  if (isServicesLoading || isSelectedServiceLoading) {
    return <ApiLoader />;
  }

  if (!selectedService) return null;
  return (
    <section>
      <Hero title="Services" breadCrumbPaths={breadCrumbPaths} />

      <div className="max-width section-padding-x my-10">
        <div>
          <h2 className="mb-4 text-center text-3xl font-bold lg:text-left">
            {selectedService?.name}
          </h2>
          {/* image */}

          <div className="mt-4 flex justify-center">
            <Image
              src={selectedService?.thumbnail}
              alt={selectedService?.name}
              width="96"
              height="96"
              className="h-auto w-3/4 border object-cover shadow"
            />
          </div>
          {/* text content */}
          <div
            className="mt-6"
            dangerouslySetInnerHTML={{
              __html: selectedService.description || "",
            }}
          />
        </div>

        {/* other services */}
        <div className="my-8">
          <div className="flex items-center gap-3">
            {/* line */}
            <div className="h-8 w-2 bg-secondary"></div>
            <h3>Other Services</h3>
          </div>

          <div className="mt-4 flex flex-col gap-8 md:flex-row">
            {otherServices
              ?.slice(0, 2)
              .map((item, i) => <ServiceCard key={i} service={item} />)}
          </div>

          <div className="mt-6 flex justify-center">
            <Link
              href="/services"
              className="custom-transition block bg-primary px-6 py-2 text-white hover:bg-secondary"
            >
              View All
            </Link>
          </div>
        </div>
      </div>
    </section>
  );
};

export default Page;
