import { TabKey } from '@/types';
import { companies, countries, products } from '@/types/data';
import { useEffect, useState } from 'react';

export function useDebouncedValue<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

export function useTabSearch(
  activeTab: TabKey,
  query: string,
  selectedCategory?: string,
  page: number = 1
) {
  const [results, setResults] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [totalPages, setTotalPages] = useState(1);

  const itemsPerPage = 10;

  useEffect(() => {
    const searchData = async () => {
      setIsLoading(true);
      setError(null);

      try {
        await new Promise((resolve) => setTimeout(resolve, 300));

        let filteredResults: any[] = [];

        switch (activeTab) {
          case 'products':
            filteredResults = products.filter(
              (p) =>
                p.name.toLowerCase().includes(query.toLowerCase()) ||
                p.description.toLowerCase().includes(query.toLowerCase())
            );
            if (selectedCategory) {
              filteredResults = filteredResults.filter((p) => p.category === selectedCategory);
            }
            break;

          case 'companies':
            filteredResults = companies.filter(
              (c) =>
                c.company_name.toLowerCase().includes(query.toLowerCase()) ||
                (c.description && c.description.toLowerCase().includes(query.toLowerCase()))
            );
            if (selectedCategory) {
              filteredResults = filteredResults.filter((c) => c.industry === selectedCategory);
            }
            break;

          case 'countries':
            filteredResults = countries.filter((c) =>
              c.name.toLowerCase().includes(query.toLowerCase())
            );
            break;
        }

        const total = Math.ceil(filteredResults.length / itemsPerPage);
        setTotalPages(total || 1);

        const startIndex = (page - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const paginatedResults = filteredResults.slice(startIndex, endIndex);

        setResults(paginatedResults);
      } catch (err) {
        setError('Failed to fetch data');
      } finally {
        setIsLoading(false);
      }
    };

    searchData();
  }, [activeTab, query, selectedCategory, page]);

  return { results, isLoading, error, totalPages };
}
