'use client';
import { ArrowLeft } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import React, { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import StatsSection from '@/components/web/home/StatsSection';
import WebLayout from '@/components/web/layout/web-layout';
import type { Service } from '@/db/schema';

const ServiceDetail = () => {
  const { id } = useParams<{ id: string }>();

  const [service, setService] = useState<Service | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [relatedServices, setRelatedServices] = useState<Service[]>([]);

  useEffect(() => {
    const fetchService = async () => {
      try {
        const singleService = await fetch(`/api/services/${id}`);
        const data = await singleService.json();

        setService(data);
      } catch (err) {
        setError('Failed to load service details.');
        throw new Error(`Error fetching service: ${err}`);
      } finally {
        setLoading(false);
      }
    };
    const fetchServices = async () => {
      try {
        const allServices = await fetch('/api/services');
        const allServicesData = await allServices.json();
        const filtered = allServicesData
          .filter((s: Service) => s.id !== id)
          .slice(0, 3);
        setRelatedServices(filtered);
      } catch (err) {
        setError('Failed to load service details.');
        throw new Error(`Error fetching service: ${err}`);
      } finally {
        setLoading(false);
      }
    };

    fetchService();
    fetchServices();
  }, [id]);

  if (error) {
    return (
      <WebLayout>
        <div className="pt-32 pb-16">
          <div className="container mx-auto px-4 text-center">
            <h1 className="mb-6 font-bold text-3xl text-oki-gray-dark">
              Error Loading Service
            </h1>
            <p className="mb-8 text-gray-600">{error}</p>
            <Link href="/services">
              <Button className="bg-oki-blue-dark text-white hover:bg-oki-blue-light">
                View All Services
              </Button>
            </Link>
          </div>
        </div>
      </WebLayout>
    );
  }

  if (!service) {
    return (
      <WebLayout>
        <div className="pt-20">
          {/* Hero Section Skeleton */}
          <section className="animate-pulse bg-gray-200 py-20 text-white">
            <div className="container mx-auto px-4">
              <div className="max-w-3xl">
                <div className="mb-4 h-6 w-40 rounded bg-gray-300" />
                <div className="mb-6 h-12 w-3/4 rounded bg-gray-300" />
                <div className="h-6 w-full rounded bg-gray-300" />
                <div className="mt-2 h-6 w-5/6 rounded bg-gray-300" />
              </div>
            </div>
          </section>

          {/* Service Description Skeleton */}
          <section className="py-16">
            <div className="container mx-auto px-4">
              <div className="grid grid-cols-1 gap-12 lg:grid-cols-3">
                <div className="lg:col-span-2">
                  <div className="mb-6 h-8 w-1/4 rounded bg-gray-200" />
                  {[...Array(3)].map((_, i) => (
                    <div
                      className="mb-4 h-4 w-full rounded bg-gray-200"
                      key={i}
                    />
                  ))}
                  <div className="mt-12 mb-6 h-8 w-1/4 rounded bg-gray-200" />
                  {[...Array(5)].map((_, i) => (
                    <div className="mb-4 flex items-center" key={i}>
                      <div className="mr-3 h-5 w-5 rounded-full bg-gray-200" />
                      <div className="h-4 w-3/4 rounded bg-gray-200" />
                    </div>
                  ))}
                </div>

                <div className="lg:col-span-1">
                  <div className="sticky top-24 rounded-lg bg-gray-100 p-6">
                    <div className="mb-6 h-6 w-1/2 rounded bg-gray-200" />
                    <div className="mb-6 h-4 w-full rounded bg-gray-200" />
                    <div className="mb-4 h-10 w-full rounded bg-gray-200" />
                    <div className="h-10 w-full rounded bg-gray-200" />
                  </div>
                </div>
              </div>
            </div>
          </section>

          {/* Related Services Skeleton */}
          <section className="bg-gray-100 py-16">
            <div className="container mx-auto px-4">
              <div className="mx-auto mb-10 h-8 w-1/3 rounded bg-gray-200" />
              <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
                {[...Array(3)].map((_, i) => (
                  <div className="rounded-lg bg-white p-6 shadow-md" key={i}>
                    <div className="mb-4 h-12 w-12 rounded-full bg-gray-200" />
                    <div className="mb-3 h-6 w-3/4 rounded bg-gray-200" />
                    <div className="mb-4 h-4 w-full rounded bg-gray-200" />
                    <div className="h-4 w-1/3 rounded bg-gray-200" />
                  </div>
                ))}
              </div>
            </div>
          </section>
        </div>
      </WebLayout>
    );
  }

  return (
    <WebLayout>
      {/* Hero Section */}
      <section
        className=" py-20 text-white"
        style={{
          backgroundImage: `linear-gradient(to right, rgba(0, 70, 173, 0.85), rgba(0, 160, 233, 0.85)), url(${service.image})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
      >
        <div className="container mx-auto px-4">
          <div className="mt-12 max-w-3xl">
            <Link
              className="mb-4 inline-flex items-center text-white/90 hover:text-white"
              href="/services"
            >
              <ArrowLeft className="mr-2" size={16} />
              <span>Back to Services</span>
            </Link>
            <h1 className="mb-6 font-bold text-4xl md:text-5xl">
              {service.name}
            </h1>
            <p className="text-white/90 text-xl" />
          </div>
        </div>
      </section>

      {/* Service Description */}
      <section className="bg-white py-16 text-black">
        <div className="container mx-auto px-4">
          <div className="grid grid-cols-1 gap-12 lg:grid-cols-3">
            <div className="lg:col-span-2">
              <Image
                alt=""
                className="pb-4"
                height={300}
                src={service?.image}
                width={300}
              />
              <h2 className="mb-6 font-bold text-3xl text-oki-gray-dark">
                Overview
              </h2>
              {service.description ? (
                <div
                  className="prose prose-gray max-w-none"
                  dangerouslySetInnerHTML={{ __html: service.description }}
                />
              ) : (
                <p className="text-gray-500">No documentation provided.</p>
              )}

              <StatsSection />
            </div>

            <div className="lg:col-span-1">
              <div className="sticky top-24 rounded-lg bg-oki-gray-light p-6">
                <h3 className="mb-6 font-semibold text-oki-gray-dark text-xl">
                  Request This Service
                </h3>
                <p className="mb-6 text-gray-600">
                  Interested in our {service?.name.toLowerCase()} services?
                  Contact us for a consultation and quote.
                </p>
                <Link href="/contact">
                  <Button className="mb-4 w-full bg-oki-red text-white hover:bg-oki-red/90">
                    Contact Us
                  </Button>
                </Link>
                <Link href="/projects">
                  <Button
                    className="w-full border-oki-blue-dark text-oki-blue-dark hover:bg-oki-blue-dark hover:text-white"
                    variant="outline"
                  >
                    View Related Projects
                  </Button>
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Related Services */}
      <section className="bg-oki-gray-light py-16">
        <div className="container mx-auto px-4">
          <h2 className="mb-10 text-center font-bold text-3xl text-oki-gray-dark">
            Other Services You Might Need
          </h2>

          {loading ? (
            <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
              {[...Array(3)].map((_, i) => (
                <div className="rounded-lg bg-white p-6 shadow-md" key={i}>
                  <div className="mb-4 h-12 w-12 animate-pulse rounded-full bg-gray-200" />
                  <div className="mb-3 h-6 w-3/4 animate-pulse rounded bg-gray-200" />
                  <div className="mb-4 h-4 w-full animate-pulse rounded bg-gray-200" />
                  <div className="h-4 w-1/3 animate-pulse rounded bg-gray-200" />
                </div>
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
              {relatedServices.map((relatedService) => (
                <div
                  className="rounded-lg bg-white p-6 shadow-md transition-shadow hover:shadow-lg"
                  key={relatedService.id}
                >
                  <div className="mb-4 text-4xl">{relatedService.icon}</div>
                  <h3 className="mb-3 font-semibold text-oki-gray-dark text-xl">
                    {relatedService.name}
                  </h3>
                  <p className="mb-4 line-clamp-6 text-gray-600">
                    {relatedService.description}
                  </p>
                  <Link
                    className="flex items-center font-medium text-oki-blue-dark transition-colors hover:text-oki-blue-light"
                    href={`/services/${relatedService.id}`}
                  >
                    <span>Learn More</span>
                    <ArrowLeft className="ml-2 rotate-180" size={16} />
                  </Link>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    </WebLayout>
  );
};

export default ServiceDetail;
