'use client';

import Link from 'next/link';
import Image from 'next/image';
import { useEffect, useState } from 'react';
import Footer from '@/components/Footer';
import PostProjectSection from '@/components/sections/PostProjectSection';
import { getCountryDataByDomain } from '@/lib/countries';

interface Category {
  id: string;
  name: string;
  slug: string;
  icon?: string;
  isActive: boolean;
  _count: {
    projects: number;
    profiles: number;
  };
}

interface CategoriesPageProps {
  params: Promise<{
    locale: string;
  }>;
}

export default function CategoriesPage({ params }: CategoriesPageProps) {
  const [locale, setLocale] = useState<string>('en');
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  

  // Get locale from params
  useEffect(() => {
    params.then(({ locale }) => setLocale(locale));
  }, [params]);

  // Fetch categories
  const fetchCategories = async () => {

     const params = new URLSearchParams({});
          const datacounter =    getCountryDataByDomain();
          if(!datacounter?.id){
              setError('Country is missing');
              return false;
          }
          params.set('countryId', datacounter?.id);
          params.set('active', 'true');

    try {
      setLoading(true);
      setError(null);



      const response = await fetch(`/api/categories?${params.toString()}`);
      const data = await response.json();

      if (response.ok) {
        setCategories(data);
      } else {
        setError('Failed to fetch categories');
      }
    } catch (error) {
      setError('Network error occurred');
      console.error('Failed to fetch categories:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  return (
    <>
      {/* Page-specific CSS */}
      <link rel="stylesheet" href="/assets/css/category.css" />
      
      {/* Hero Section */}
      <section className="inner-hero-wrapper">
        <div className="container">
          <div className="row">
            <div className="col-12 col-md-7 col-lg-8 align-self-center">
              <div className="hero-content">
                <h1>All Service category</h1>
                <p>Explore service categories to find skilled professionals for every project</p>
              </div>
            </div>
            <div className="col-12 col-md-5 col-lg-4 align-self-end">
              <div className="inner-hero-img text-center pt-3">
                <img src="/assets/image/service-banner-img.svg" alt="service-banner-img" />
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Categories Section */}
      <section className="category-wrapper pt-120">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="category-listing">
                {loading ? (
                  <div className="text-center p-4">
                    <div className="spinner-border" role="status">
                      <span className="sr-only">Loading...</span>
                    </div>
                  </div>
                ) : error ? (
                  <div className="text-center p-4">
                    <div className="alert alert-danger">{error}</div>
                  </div>
                ) : (
                  <ul className="category-list-wrap">
                    {categories.map((category) => (
                      <li key={category.id}>
                        <div className="cat-img">
                          {category.icon && (
                            <img 
                              src={`/assets/image/category/${category.icon}`} 
                              alt={category.name} 
                            />
                          )}
                        </div>
                        <Link 
                          href={`/${locale}/projects?categoryId=${category.id}`} 
                          className="stretched-link"
                        >
                          {category.name}
                        </Link>
                        <div className="totalpro">{category._count.projects} Projects</div>
                      </li>
                    ))}
                  </ul>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Post Project Section */}
      <PostProjectSection locale={locale} />

      {/* Footer */}
      <Footer locale={locale} />

      <style jsx>{`
        .spinner-border {
          width: 3rem;
          height: 3rem;
          border: 0.25em solid currentColor;
          border-right-color: transparent;
          border-radius: 50%;
          animation: spinner-border 0.75s linear infinite;
        }
        
        @keyframes spinner-border {
          to { transform: rotate(360deg); }
        }
        
        .sr-only {
          position: absolute;
          width: 1px;
          height: 1px;
          padding: 0;
          margin: -1px;
          overflow: hidden;
          clip: rect(0, 0, 0, 0);
          white-space: nowrap;
          border: 0;
        }
        
        .alert {
          padding: 1rem;
          border: 1px solid transparent;
          border-radius: 0.375rem;
        }
        
        .alert-danger {
          color: #721c24;
          background-color: #f8d7da;
          border-color: #f5c6cb;
        }
      `}</style>
    </>
  );
}
