"use client";

import React, { useEffect, useState } from "react";
import Title from "../../lib_components/title";
import Text from "../../lib_components/text";
import type { ProductTypes } from "@/types";
import ProductCard from "../../cards/productCard";
import { LoadingSkeleton } from "@/components/loadingProduct";
import { EmptyState } from "@/components/emptyState";
import { usePathname } from "next/navigation";
import { baseUrl } from "@/data/url";

// Kerakli tartib (id lar bo'yicha)
const CATEGORY_ORDER: number[] = [1, 2, 3, 4, 6, 5, 8, 9, 23, 11, 12, 10, 14, 26, 17, 13, 20, 19, 21, 28];

function sortByCustomOrder(data: ProductTypes[]): ProductTypes[] {
  return [...data].sort((a, b) => {
    const indexA = CATEGORY_ORDER.indexOf(a.id);
    const indexB = CATEGORY_ORDER.indexOf(b.id);

    // Agar id topilmasa - oxiriga surish
    if (indexA === -1) return 1;
    if (indexB === -1) return -1;

    return indexA - indexB;
  });
}

export default function Products() {
  const [cars, setCars] = useState<ProductTypes[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const pathname = usePathname();
  const lang = pathname.split("/")[1];

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        setLoading(true);
        setError(null);

        const response = await fetch(baseUrl, {
          headers: {
            "Accept-Language": lang,
          },
        });

        if (!response.ok) {
          throw new Error("Server xatosi");
        }

        const data = await response.json();

        if (data?.data && data.data.length > 0) {
          // ✅ Qayta tartiblash
          const sorted = sortByCustomOrder(data.data);
          setCars(sorted);
        } else {
          setCars([]);
        }
      } catch (error) {
        setError(error instanceof Error ? error.message : "Noma'lum xatolik");
      } finally {
        setLoading(false);
      }
    };

    fetchProducts();
  }, [lang]);

  return (
    <div dir="ltr" className="max-w-[1200px] w-full mx-auto">
      <div className="flex flex-col mb-10">
        <div className="flex items-center justify-center w-full">
          <div className="text-[#f2a01c] px-2 text-[18px] font-semibold">
            <Text txt="katalog" />
          </div>
        </div>
        <Title text="pricing-h2" />
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-600 text-center">
            <Text txt="downloadError" /> : {error}
          </p>
        </div>
      )}

      <div className="px-4 grid gap-5 grid-cols-1 place-content-center min-[500px]:grid-cols-2 min-lg:grid-cols-4 min-[1210px]:grid-cols-4">
        {loading ? (
          <LoadingSkeleton />
        ) : cars.length > 0 ? (
          cars.map((item: ProductTypes, index: number) => (
            <div key={item.id || index}>
              <ProductCard data={item} />
            </div>
          ))
        ) : (
          <EmptyState />
        )}
      </div>
    </div>
  );
}