'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { Category } from '@/types/category';
import { getCountryDataByDomain } from '@/lib/countries';
import { useTranslations } from 'next-intl';

interface FeaturedCategoriesSectionProps {
  locale: string;
}

export default function FeaturedCategoriesSection({ locale }: FeaturedCategoriesSectionProps) {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const t = useTranslations();

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

      try {
        setLoading(true);

        const response = await fetch(`/api/categories/featured?${params.toString()}`);
        
        if (!response.ok) {
          throw new Error('Failed to fetch categories');
        }
        
        const data = await response.json();
        
        if (data.success) {
          setCategories(data.data);
        } else {
          throw new Error(data.error || 'Failed to fetch categories');
        }
      } catch (err) {
        console.error('Error fetching categories:', err);
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    fetchCategories();
  }, []);

  if (loading) {
    return (
      <section className="categories-wrapper pt-120">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="heading-box">
                <h2 className="mb-0">{t('home.categories.featured')}</h2>
                <div className="h-link">
                  <Link href={`/${locale}/categories`}>
                    {t("home.categories.view_all")}
                    <svg width="24" height="16" viewBox="0 0 24 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M1 8L23 8" stroke="#0E9493" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                      <path d="M16 1L23 8L16 15" stroke="#0E9493" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>                                    
                  </Link>
                </div>
              </div>
              <div className="category-listing">
                <div className="d-flex justify-content-center align-items-center" style={{ minHeight: '200px' }}>
                  <div className="spinner-border text-primary" role="status">
                    <span className="visually-hidden">Loading...</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  if (error) {
    return (
      <section className="categories-wrapper pt-120">
        <div className="container">
          <div className="row">
            <div className="col-12">
              <div className="heading-box">
                <h2 className="mb-0">{t('home.categories.featured')}</h2>
                <div className="h-link">
                  <Link href={`/${locale}/categories`}>
                    {t("home.categories.view_all")}
                    <svg width="24" height="16" viewBox="0 0 24 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M1 8L23 8" stroke="#0E9493" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                      <path d="M16 1L23 8L16 15" stroke="#0E9493" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>                                    
                  </Link>
                </div>
              </div>
              <div className="category-listing">
                <div className="alert alert-danger text-center" role="alert">
                  <h5>Unable to load categories</h5>
                  <p className="mb-0">{error}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section className="categories-wrapper pt-120">
      <div className="container">
        <div className="row">
          <div className="col-12">
            <div className="heading-box">
              <h2 className="mb-0">{t('home.categories.featured')}</h2>
              <div className="h-link">
                <Link href={`/${locale}/categories`}>
                  {t("home.categories.view_all")}
                  <svg width="24" height="16" viewBox="0 0 24 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M1 8L23 8" stroke="#0E9493" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                    <path d="M16 1L23 8L16 15" stroke="#0E9493" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>                                    
                </Link>
              </div>
            </div>
            <div className="category-listing">
              <ul className="category-list-wrap">
                {categories.map((category) => (
                  <li key={category.id}>
                    <div className="cat-img">
                      <img 
                        src={category.image} 
                        alt={category.name}
                        onError={(e) => {
                          const target = e.target as HTMLImageElement;
                          target.src = '/assets/image/category/default.svg';
                        }}
                      />
                    </div>
                    <Link 
                      href={`/${locale}/projects?categoryId=${category.id}`} 
                      className="stretched-link"
                    >
                      {category.name}
                    </Link>
                    <div className="totalpro">
                      {category.projectCount} Project{category.projectCount !== 1 ? 's' : ''}
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}