'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { Search, Filter, SlidersHorizontal, ChevronLeft, ChevronRight } from 'lucide-react';
import { VehicleCard } from '@/components/public/vehicle-card';
import { useLanguage } from '@/lib/i18n/language-context';

function getCategoryDisplayName(cat: any, locale: string) {
  if (locale === 'en' && cat?.nameEn) return cat.nameEn;
  return cat?.name ?? '';
}

export function InventoryClient({ vehicles = [], categories = [], makes = [], years = [], engines = [], transmissions = [], totalCount = 0, currentParams = {} }: any) {
  const router = useRouter();
  const [search, setSearch] = useState(currentParams?.search ?? '');
  const [showFilters, setShowFilters] = useState(false);
  const currentPage = parseInt(currentParams?.page ?? '1');
  const perPage = 12;
  const totalPages = Math.ceil((totalCount ?? 0) / perPage);
  const { t, locale } = useLanguage();

  // Find subcategories for currently selected category
  const selectedCat = (categories ?? []).find((c: any) => c?.slug === currentParams?.category);
  const subcategories = selectedCat?.children ?? [];

  const updateFilter = (key: string, value: string) => {
    const params = new URLSearchParams();
    Object.keys(currentParams ?? {})?.forEach((k: string) => {
      if (k !== key && k !== 'page') params.set(k, currentParams[k]);
    });
    if (value) params.set(key, value);
    // Clear subcategory when changing category
    if (key === 'category') params.delete('subcategory');
    router.push(`/inventory?${params.toString()}`);
  };

  const handleSearch = (e: any) => {
    e?.preventDefault?.();
    updateFilter('search', search ?? '');
  };

  return (
    <div className="min-h-screen bg-[#faf5ef]">
      {/* Header */}
      <div className="bg-[#1a1a1a] py-12">
        <div className="max-w-[1200px] mx-auto px-4">
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
            <h1 className="font-display text-3xl md:text-4xl font-bold text-white tracking-tight">{t.inventory.title} <span className="text-red-500">{t.inventory.titleHighlight}</span></h1>
            <p className="text-gray-400 mt-2">{t.inventory.subtitle}</p>
          </motion.div>
          {/* Search */}
          <form onSubmit={handleSearch} className="mt-6 flex gap-2 max-w-lg">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                value={search}
                onChange={(e: any) => setSearch(e?.target?.value ?? '')}
                placeholder={t.inventory.searchPlaceholder}
                className="w-full pl-10 pr-4 py-3 rounded-lg bg-white/10 text-white placeholder:text-gray-500 border border-white/10 focus:border-red-500 focus:outline-none text-sm"
              />
            </div>
            <button type="submit" className="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg font-semibold text-sm transition">
              {t.inventory.search}
            </button>
          </form>
        </div>
      </div>

      <div className="max-w-[1200px] mx-auto px-4 py-8">
        {/* Filter toggle */}
        <div className="flex items-center justify-between mb-6">
          <p className="text-sm text-gray-500">{totalCount ?? 0} {(totalCount ?? 0) !== 1 ? t.inventory.equipmentPlural : t.inventory.equipment} {(totalCount ?? 0) !== 1 ? t.inventory.foundPlural : t.inventory.found}</p>
          <button onClick={() => setShowFilters(!showFilters)} className="flex items-center gap-2 text-sm font-medium text-gray-700 hover:text-red-600 transition px-4 py-2 rounded-lg bg-white shadow-sm">
            <SlidersHorizontal className="w-4 h-4" /> {t.inventory.filters}
          </button>
        </div>

        {/* Filters */}
        {showFilters && (
          <motion.div initial={{ height: 0, opacity: 0 }} animate={{ height: 'auto', opacity: 1 }} className="bg-white rounded-xl shadow-sm p-6 mb-6">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              {/* Category */}
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1 block">{t.inventory.category}</label>
                <select onChange={(e: any) => updateFilter('category', e?.target?.value ?? '')} value={currentParams?.category ?? ''} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
                  <option value="">{t.inventory.allCategories}</option>
                  {(categories ?? [])?.filter((c: any) => !c?.parentId)?.map((c: any) => (
                    <option key={c?.id} value={c?.slug}>{getCategoryDisplayName(c, locale)}</option>
                  ))}
                </select>
              </div>
              {/* Subcategory - only show when category with children is selected */}
              {subcategories.length > 0 && (
                <div>
                  <label className="text-xs font-medium text-gray-500 mb-1 block">{t.inventory.subcategory}</label>
                  <select onChange={(e: any) => updateFilter('subcategory', e?.target?.value ?? '')} value={currentParams?.subcategory ?? ''} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
                    <option value="">{t.inventory.allSubcategories}</option>
                    {subcategories.map((sub: any) => (
                      <option key={sub?.id} value={sub?.slug}>{getCategoryDisplayName(sub, locale)}</option>
                    ))}
                  </select>
                </div>
              )}
              {/* Make */}
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1 block">{t.inventory.make}</label>
                <select onChange={(e: any) => updateFilter('make', e?.target?.value ?? '')} value={currentParams?.make ?? ''} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
                  <option value="">{t.inventory.allMakes}</option>
                  {(makes ?? [])?.map((m: string) => <option key={m} value={m}>{m}</option>)}
                </select>
              </div>
              {/* Year */}
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1 block">{t.inventory.year}</label>
                <select onChange={(e: any) => updateFilter('year', e?.target?.value ?? '')} value={currentParams?.year ?? ''} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
                  <option value="">{t.inventory.allYears}</option>
                  {(years ?? [])?.map((y: number) => <option key={y} value={y}>{y}</option>)}
                </select>
              </div>
              {/* Engine */}
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1 block">{t.inventory.engine}</label>
                <select onChange={(e: any) => updateFilter('engine', e?.target?.value ?? '')} value={currentParams?.engine ?? ''} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
                  <option value="">{t.inventory.allEngines}</option>
                  {(engines ?? [])?.map((e: string) => <option key={e} value={e}>{e}</option>)}
                </select>
              </div>
              {/* Transmission */}
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1 block">{t.inventory.transmission}</label>
                <select onChange={(e: any) => updateFilter('transmission', e?.target?.value ?? '')} value={currentParams?.transmission ?? ''} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
                  <option value="">{t.inventory.allTransmissions}</option>
                  {(transmissions ?? [])?.map((tr: string) => <option key={tr} value={tr}>{tr}</option>)}
                </select>
              </div>
              {/* Status */}
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1 block">{t.inventory.status}</label>
                <select onChange={(e: any) => updateFilter('status', e?.target?.value ?? '')} value={currentParams?.status ?? ''} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm">
                  <option value="ALL">{t.inventory.allStatuses}</option>
                  <option value="AVAILABLE">{locale === 'es' ? 'Disponible' : 'Available'}</option>
                  <option value="SOLD">{locale === 'es' ? 'Vendido' : 'Sold'}</option>
                </select>
              </div>
              {/* Max Price */}
              <div>
                <label className="text-xs font-medium text-gray-500 mb-1 block">{t.inventory.maxPrice}</label>
                <input type="number" placeholder={t.inventory.noLimit} onChange={(e: any) => updateFilter('maxPrice', e?.target?.value ?? '')} value={currentParams?.maxPrice ?? ''} className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm" />
              </div>
            </div>
          </motion.div>
        )}

        {/* Vehicle grid */}
        {(vehicles?.length ?? 0) > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {(vehicles ?? [])?.map((v: any) => <VehicleCard key={v?.id} vehicle={v} />)}
          </div>
        ) : (
          <div className="text-center py-20">
            <Filter className="w-12 h-12 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-600">{t.inventory.noResults}</h3>
            <p className="text-gray-400 text-sm mt-1">{t.inventory.noResultsHint}</p>
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex justify-center items-center gap-2 mt-10">
            <button disabled={currentPage <= 1} onClick={() => updateFilter('page', String(currentPage - 1))} className="p-2 rounded-lg bg-white shadow-sm hover:shadow-md disabled:opacity-50 transition">
              <ChevronLeft className="w-5 h-5" />
            </button>
            <span className="text-sm text-gray-600 px-4">{t.inventory.page} {currentPage} {t.inventory.of} {totalPages}</span>
            <button disabled={currentPage >= totalPages} onClick={() => updateFilter('page', String(currentPage + 1))} className="p-2 rounded-lg bg-white shadow-sm hover:shadow-md disabled:opacity-50 transition">
              <ChevronRight className="w-5 h-5" />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
