"use client";

import { useState, useMemo, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import type { NormalizedCar } from "@/lib/payload-helpers";

const CATEGORY_LABELS: Record<string, string> = {
  suv: "SUV", sports: "Sports", luxury: "Luxury",
  convertible: "Convertible", coupe: "Coupe", sedan: "Sedan",
};

const SORT_OPTIONS = [
  { value: "price-asc",  label: "Price: Low to High" },
  { value: "price-desc", label: "Price: High to Low" },
  { value: "name-asc",   label: "Name A–Z" },
];

interface Props {
  cars: NormalizedCar[]
  brands: Array<{ name: string; urlSlug: string }>
  carTypes: Array<{ key: string; label: string; urlSlug: string }>
}

export default function AllCarsClient({ cars, brands, carTypes }: Props) {
  const searchParams = useSearchParams();
  const [brand, setBrand]       = useState("");
  const [category, setCategory] = useState("");
  const [sort, setSort]         = useState("price-asc");
  const [query, setQuery]       = useState(() => searchParams.get("q") ?? "");

  useEffect(() => {
    const q = searchParams.get("q")
    if (q) setQuery(q)
  }, [searchParams]);

  const filtered = useMemo(() => {
    let list = [...cars];
    if (brand)    list = list.filter(c => c.brand === brand);
    if (category) list = list.filter(c => c.category === category);
    if (query)    list = list.filter(c => c.title.toLowerCase().includes(query.toLowerCase()));
    if (sort === "price-asc")  list.sort((a, b) => (a.priceDay ?? 999999) - (b.priceDay ?? 999999));
    if (sort === "price-desc") list.sort((a, b) => (b.priceDay ?? 0)      - (a.priceDay ?? 0));
    if (sort === "name-asc")   list.sort((a, b) => a.title.localeCompare(b.title));
    return list;
  }, [cars, brand, category, sort, query]);

  function clearFilters() { setBrand(""); setCategory(""); setQuery(""); }

  return (
    <>
      {/* Page header */}
      <div className="bg-navy-900 text-white py-10">
        <div className="section-wrap">
          <nav className="flex items-center gap-1.5 text-xs text-navy-300 mb-3">
            <Link href="/" className="hover:text-white">Home</Link>
            <span>/</span>
            <span>All Cars</span>
          </nav>
          <h1 className="text-3xl font-black mb-2">Rent a Car in Dubai</h1>
          <p className="text-navy-300 text-sm max-w-xl">
            Browse {cars.length}+ cars: luxury, SUV, sports, convertibles and more. Free delivery across Dubai.
          </p>
        </div>
      </div>

      <div className="section-wrap py-6">
        {/* Filters bar */}
        <div className="bg-white rounded-2xl border border-[#e2e6ed] p-4 mb-6 shadow-sm">
          <div className="flex flex-wrap gap-3 items-end">
            <div className="flex-1 min-w-[180px]">
              <label className="block text-xs font-semibold text-[#5c6472] mb-1.5">Search</label>
              <input
                type="text"
                value={query}
                onChange={e => setQuery(e.target.value)}
                placeholder="e.g. Lamborghini Urus"
                className="w-full border border-[#e2e6ed] rounded-xl px-3 py-2 text-sm focus:outline-none focus:border-brand"
              />
            </div>
            <div className="min-w-[160px]">
              <label className="block text-xs font-semibold text-[#5c6472] mb-1.5">Brand</label>
              <select
                value={brand}
                onChange={e => setBrand(e.target.value)}
                className="w-full border border-[#e2e6ed] rounded-xl px-3 py-2 text-sm bg-white focus:outline-none focus:border-brand"
              >
                <option value="">All Brands</option>
                {brands.map(b => <option key={b.urlSlug} value={b.name}>{b.name}</option>)}
              </select>
            </div>
            <div className="min-w-[150px]">
              <label className="block text-xs font-semibold text-[#5c6472] mb-1.5">Type</label>
              <select
                value={category}
                onChange={e => setCategory(e.target.value)}
                className="w-full border border-[#e2e6ed] rounded-xl px-3 py-2 text-sm bg-white focus:outline-none focus:border-brand"
              >
                <option value="">All Types</option>
                {carTypes.map(ct => <option key={ct.key} value={ct.key}>{ct.label}</option>)}
              </select>
            </div>
            <div className="min-w-[180px]">
              <label className="block text-xs font-semibold text-[#5c6472] mb-1.5">Sort by</label>
              <select
                value={sort}
                onChange={e => setSort(e.target.value)}
                className="w-full border border-[#e2e6ed] rounded-xl px-3 py-2 text-sm bg-white focus:outline-none focus:border-brand"
              >
                {SORT_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            </div>
            {(brand || category || query) && (
              <button
                onClick={clearFilters}
                className="text-sm text-[#5c6472] hover:text-[#1a1f2e] underline self-end pb-2"
              >
                Clear
              </button>
            )}
          </div>
        </div>

        {/* Result count */}
        <div className="flex items-center justify-between mb-4">
          <p className="text-sm text-[#5c6472]">
            Showing <strong className="text-[#1a1f2e]">{filtered.length}</strong> cars
            {brand    && <> · <span className="text-brand">{brand}</span></>}
            {category && <> · <span className="text-brand">{CATEGORY_LABELS[category] ?? category}</span></>}
          </p>
        </div>

        {/* Category quick-links */}
        {!brand && !category && !query && (
          <div className="flex gap-2 flex-wrap mb-6">
            {carTypes.map(ct => {
              const count = cars.filter(c => c.category === ct.key).length;
              return (
                <button key={ct.key} onClick={() => setCategory(ct.key)} className="pill-tab">
                  {ct.label} <span className="text-[#adb7c7] text-xs ml-0.5">({count})</span>
                </button>
              );
            })}
          </div>
        )}

        {/* Grid */}
        {filtered.length === 0 ? (
          <div className="text-center py-16 text-[#5c6472]">
            <p className="text-lg font-semibold mb-2">No cars found</p>
            <button onClick={clearFilters} className="btn-primary text-sm mt-2">Clear filters</button>
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
            {filtered.map(car => (
              <Link key={car.slug} href={`/car/${car.slug}`} className="car-card flex flex-col group">
                <div className="relative bg-[#141414] aspect-[4/3] overflow-hidden">
                  {car.image ? (
                    <Image
                      src={car.image}
                      alt={`${car.title} rental Dubai`}
                      fill
                      className="object-cover group-hover:scale-105 transition-transform duration-300"
                      sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-[#333333]">
                      <svg viewBox="0 0 120 60" className="w-24 h-12" fill="currentColor">
                        <path d="M14 38l10-18h62l10 18H14z" opacity=".25"/>
                        <circle cx="28" cy="46" r="8" opacity=".4"/>
                        <circle cx="92" cy="46" r="8" opacity=".4"/>
                      </svg>
                    </div>
                  )}
                  {car.noDeposit && (
                    <span className="absolute top-2 left-2 bg-emerald-500 text-white text-xs font-bold px-2 py-0.5 rounded-full">
                      No Deposit
                    </span>
                  )}
                  <span className="absolute top-2 right-2 bg-white/90 backdrop-blur-sm text-[#5c6472] text-xs font-semibold px-2 py-0.5 rounded-full capitalize">
                    {CATEGORY_LABELS[car.category] ?? car.category}
                  </span>
                </div>
                <div className="p-3 flex flex-col flex-1">
                  <p className="text-xs font-semibold text-[#5c6472] uppercase tracking-wide mb-0.5">{car.brand}</p>
                  <p className="font-bold text-[#1a1f2e] text-sm leading-tight mb-2 flex-1">{car.title}</p>
                  <div className="flex gap-2 text-xs text-[#5c6472] mb-2.5">
                    <span>👤{car.passengers}</span>
                    <span>🚪{car.doors}</span>
                    <span>⚙️ {car.transmission}</span>
                  </div>
                  <div className="flex items-end justify-between">
                    <div>
                      <p className="text-xs text-[#5c6472]">from</p>
                      <p className="text-brand font-black text-base">
                        AED {car.priceDay?.toLocaleString() ?? "N/A"}
                        <span className="text-[#5c6472] font-normal text-xs">/day</span>
                      </p>
                    </div>
                    <span className="text-xs font-semibold text-brand bg-brand/10 px-2 py-1 rounded-lg">Book →</span>
                  </div>
                </div>
              </Link>
            ))}
          </div>
        )}

        {/* SEO text block */}
        <section className="mt-14 bg-[#f8f9fb] rounded-2xl p-6 border border-[#e2e6ed]">
          <h2 className="text-xl font-black text-[#1a1f2e] mb-3">Rent a Car in Dubai | NCK Car Rental</h2>
          <p className="text-sm text-[#5c6472] leading-relaxed mb-3">
            NCK Car Rental offers the largest fleet of luxury, sports, SUV and economy cars for rent in Dubai.
            Choose from {cars.length}+ vehicles with free delivery to your door, no deposit on selected cars,
            and 24/7 customer support.
          </p>
          <p className="text-sm text-[#5c6472] leading-relaxed">
            We serve all areas including Dubai Marina, Downtown Dubai, JBR, Palm Jumeirah, DIFC, Business Bay,
            and Dubai Airport. All cars come fully insured and maintained to the highest standards.
          </p>
          <div className="flex flex-wrap gap-2 mt-4">
            {carTypes.map(ct => (
              <Link
                key={ct.key}
                href={`/cartype/${ct.urlSlug}`}
                className="text-xs text-brand border border-brand/20 bg-brand/5 px-3 py-1 rounded-full hover:bg-brand hover:text-white transition-colors"
              >
                {ct.label} Cars for Rent
              </Link>
            ))}
          </div>
        </section>
      </div>
    </>
  );
}
