"use client";

import Text from "@/components/lib_components/text";
import Image from "next/image";
import React, { useEffect, useState } from "react";
import CarRentalModal from "@/components/lib_components/carRentalModal";
import { usePathname, useParams } from "next/navigation";
import { logoImg } from "@/assets";
import { useSubCategory } from "@/store/subCategory";
import { minimumValues } from "@/data/minimimValues";
import { useTranslations } from "next-intl";
import { LoadingSkeleton } from "@/components/loadingProduct";
import { EmptyState } from "@/components/emptyState";
import { ErrorState } from "@/components/errorState";

const baseUrl = "https://api.spes-texnika.uz/api/v1/products/";

type Lang = "uz" | "ru" | "en";
const validLangs: Lang[] = ["uz", "ru", "en"];

function checkCategory(categoryName: string | undefined, lang: string) {
  if (!categoryName || !validLangs.includes(lang as Lang)) {
    return { isMinimum: false, text: "" };
  }
  const validLang = lang as Lang;
  const matched = minimumValues[validLang].find(
    (item: string) => item === categoryName,
  );
  if (matched)
    return { isMinimum: true, text: minimumValues.values[validLang] };
  return { isMinimum: false, text: "" };
}

export default function CarDetailPage() {
  const t = useTranslations();
  const [modalOpen, setModalOpen] = useState<boolean>(false);

  const initialSubCategory = useSubCategory(
    (state) => state.initialSubCategory,
  );
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const pathname = usePathname();
  const params = useParams();
  const lang = pathname.split("/")[1];
  const carId = params.carDeatil as string;
  const [cars, setCars] = useState<any[]>([]);

  const fetchProducts = async () => {
    if (!carId) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);

      const response = await fetch(`${baseUrl}${carId}/by-subcategory/`, {
        headers: {
          "Accept-Language": lang,
        },
      });

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

      const result = await response.json();
      console.log("backend full response: ", result);
      console.log("backend Data: ", result?.data);

      if (result?.data) {
        if (Array.isArray(result.data)) {
          setCars(result.data);
        } else {
          setCars([result.data]);
        }
      } else {
        setCars([]);
      }
    } catch (err) {
      console.log("Xatolik: ", err);
      setError(err instanceof Error ? err.message : "Noma'lum xatolik");
      setCars([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProducts();
  }, [carId, lang]);

  if (loading) {
    return (
      <div className="my-10 max-w-[1200px] w-full mx-auto grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 px-2">
        <LoadingSkeleton />
      </div>
    );
  }

  if (error) {
    return (
      <div className="my-10 max-w-[1200px] w-full mx-auto px-2">
        <ErrorState message={error} onRetry={fetchProducts} />
      </div>
    );
  }

  const firstData = cars[0]?.data[0];
  console.log("First Data: ", firstData);

  if (!firstData) {
    return (
      <div className="my-10 max-w-[1200px] w-full mx-auto px-2">
        <EmptyState />
      </div>
    );
  }

  const { isMinimum, text } = checkCategory(initialSubCategory.name, lang);

  return (
    <div
      dir="ltr"
      className="my-10 max-w-[1200px] w-full mx-auto space-y-8 flex flex-col items-start justify-center px-2"
    >
      <div className="text-2xl font-bold w-full text-center text-secondary mb-10">
        <Text txt={""} />
      </div>

      <div className="flex flex-col md:flex-row md:items-start items-center gap-6 justify-center w-full">
        <div className="max-w-[600px] w-full h-auto">
          <Image
            src={firstData?.image ? firstData?.image : logoImg}
            alt={firstData?.name ? firstData?.name : "image"}
            width={600}
            height={200}
            className="rounded-lg object-contain border border-gray-200 w-full"
          />
        </div>

        <div className="lg:space-y-6 space-y-3 w-full">
          <div className="text-lg font-semibold flex gap-2">
            {isMinimum ? <p>{text}</p> : <Text txt="hour-price" />} :
            <span className="font-medium flex gap-2 text-gray-500">
              {firstData.price
                ? Math.round(Number(firstData.price)).toLocaleString("ru-RU")
                : ""}
              <Text txt="wallet" />
            </span>
          </div>
          {!isMinimum && (
            <div className="text-lg font-semibold flex gap-2">
              <Text txt="min-time" />
              <span className="font-medium flex gap-2 text-gray-500">
                {firstData.minimal_order}
                <Text txt="time" />
              </span>
            </div>
          )}

          <div className="space-y-2 text-gray-500 text-lg">
            <Text txt="note1" />
            <Text txt="note2" />
          </div>

          <div className="flex gap-6">
            <button
              onClick={() => setModalOpen(true)}
              className="bg-secondary p-3 px-6 rounded-lg border-2 border-secondary text-white
                hover:cursor-pointer hover:bg-white hover:text-secondary transition-all"
            >
              <Text txt="book" />
            </button>
          </div>
        </div>
      </div>

      {firstData?.features.length > 0 && (
        <div className="w-full border-t border-gray-300 pt-6">
          <h2 className="text-xl font-semibold mb-4 text-secondary">
            {t("tech-features")}
          </h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 text-gray-700">
            {firstData?.features?.map((item: any) => (
              <div
                key={item.id}
                className="p-3 rounded-md bg-gray-50 border border-gray-200 hover:bg-gray-100 transition"
              >
                <p className="font-medium">{item?.name}:</p>
                <p className="text-gray-600">{item?.value}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      <CarRentalModal
        car={firstData}
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
      />
    </div>
  );
}
