'use client';

import { product_api } from '@/shared/config/api/product/api';
import { ProductListResult } from '@/shared/config/api/product/type';
import { useRouter } from '@/shared/config/i18n/navigation';
import { Input } from '@/shared/ui/input';
import { ProductCard } from '@/widgets/categories/ui/product-card';
import { useQuery } from '@tanstack/react-query';
import { Search, X } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';

const SearchResult = () => {
  const router = useRouter();
  const t = useTranslations();
  const searchParams = useSearchParams();

  const query = searchParams.get('search') || '';
  const [inputValue, setInputValue] = useState(query);

  /* 🔹 URL → Input sync */
  useEffect(() => {
    setInputValue(query);
  }, [query]);

  /* 🔹 Debounce → Input → URL sync */
  useEffect(() => {
    const delay = setTimeout(() => {
      if (!inputValue.trim()) {
        router.replace('/search');
      } else {
        router.replace(`/search?search=${encodeURIComponent(inputValue)}`);
      }
    }, 400);

    return () => clearTimeout(delay);
  }, [inputValue, router]);

  /* 🔹 Default product list */
  const { data: productList, isLoading: listLoading } = useQuery({
    queryKey: ['product_list'],
    queryFn: () => product_api.list({ page: 1, page_size: 12 }),
    select: (res) => res.data.results,
    enabled: !query,
    staleTime: 0,
  });

  /* 🔹 Search query */
  const { data: searchList, isLoading: searchLoading } = useQuery({
    queryKey: ['search', query, inputValue],
    queryFn: () =>
      product_api.search({
        search: inputValue, // agar backend `q` kutsa → q: query
        page: 1,
        page_size: 12,
      }),
    select: (res) => res.data.products,
    enabled: !!query,
    staleTime: 0,
  });

  const data = query ? (searchList ?? []) : (productList ?? []);
  const isLoading = query ? searchLoading : listLoading;

  /* 🔹 Handlers */
  const clearSearch = () => {
    setInputValue('');
    router.replace('/search');
  };

  return (
    <div className="custom-container min-h-screen">
      {/* 🔍 Search input */}
      <div className="mb-6">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-slate-400" />

          <Input
            value={inputValue}
            placeholder={t('Mahsulot nomi')}
            onChange={(e) => setInputValue(e.target.value)}
            className="w-full pl-10 pr-10 h-12"
          />

          {inputValue && (
            <button
              onClick={clearSearch}
              className="absolute right-3 top-1/2 -translate-y-1/2"
            >
              <X className="w-5 h-5" />
            </button>
          )}
        </div>
      </div>

      {/* 🔹 Content */}
      {isLoading ? (
        <div className="text-center py-20">{t('Yuklanmoqda')}...</div>
      ) : data.length > 0 ? (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
          {data.map((product) => (
            <ProductCard
              key={(product as ProductListResult).id}
              product={product as ProductListResult}
            />
          ))}
        </div>
      ) : (
        <div className="text-center py-20">{t('Natija topilmadi')}</div>
      )}
    </div>
  );
};

export default SearchResult;
