'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 { Button } from '@/shared/ui/button';
import { Input } from '@/shared/ui/input';
import { ProductCard } from '@/widgets/categories/ui/product-card';
import { useQuery } from '@tanstack/react-query';
import { Search } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
import { useState } from 'react';

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

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

  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,
  });

  const { data: searchList, isLoading: searchLoading } = useQuery({
    queryKey: ['search', query],
    queryFn: () =>
      product_api.search({
        search: 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;

  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"
          />

          <Button
            className="absolute top-0 right-0 h-12 cursor-pointer"
            onClick={() =>
              router.replace(`/search?search=${encodeURIComponent(inputValue)}`)
            }
          >
            {t('Qidirish')}
          </Button>

          {/* {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;
