"use client";
import React, { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { useRouter } from "next/navigation";
import { Icons } from "@/components/icons";
import apis from "@/utils/apis";
import { Heart } from "lucide-react";
import {
  Pagination,
  PaginationContent,
  PaginationLink,
  PaginationItem,
  PaginationPrevious,
  PaginationNext,
  PaginationEllipsis,
} from "@/components/ui/pagination";
import { getValidImage } from "@/lib/utils";

const FavouriteCard = ({ data, type, onFavourite }: any) => {
  const router = useRouter();

  const isRestaurant = type === "restaurant";
  const isDish = type === "dishes";
  const isGrocery = type !== "restaurant" && type !== "dishes";
  const rating = isGrocery ? (data?.store?.rating || 0) : (data?.rating || 0);

  const imageUrl = (() => {
    if (isRestaurant) {
      return getValidImage(typeof data?.image === "string" ? data.image : "");
    }
    if (isDish) {
      return getValidImage(
        Array.isArray(data?.image) ? data.image[0] : data?.image || ""
      );
    }
    if (isGrocery) {
      return getValidImage(data?.imageUrl || "");
    }
    return getValidImage("");
  })();

  const handleClick = () => {
    if (isRestaurant) {
      router.push(`/restaurant?id=${data._id}`);
    } else if (isDish) {
      router.push(`/restaurant?id=${data.restaurant_id}`);
    } else if (isGrocery) {
      router.push(`/grocery/product/${data._id}?restaurantId=${data.restaurant_id || data.store_id || data.store?._id}`);
    }
  };

  const handleFavouriteClick = (e: any) => {
    e.stopPropagation();
    onFavourite(data._id, data.is_fav, type);
  };

  return (
    <div
      className="w-full sm:w-[400px] h-auto flex flex-col sm:flex-row border border-gray-300 rounded-lg overflow-hidden shadow-sm transition hover:shadow-md cursor-pointer bg-white"
      onClick={handleClick}
    >
      {/* Image */}
      <div
        className="w-full sm:w-[160px] h-[160px] relative flex-shrink-0"
        style={{
          backgroundImage: `url("${imageUrl}")`,
          backgroundSize: "cover",
          backgroundPosition: "center",
        }}
      >
        <div
          className="absolute top-2 right-2 bg-white rounded-full p-1.5 shadow-md z-10 hover:scale-110 transition-transform"
          onClick={handleFavouriteClick}
        >
          {data?.is_fav ? (
            <div className="text-primary"><Icons.Heart /></div>
          ) : (
            <Heart size={15} className="text-gray-400" />
          )}
        </div>
      </div>

      {/* Content */}
      <div className="p-3 flex flex-col justify-between w-full min-w-0">
        <div>
          <p className="text-lg font-bold text-gray-900 truncate">
            {isRestaurant ? data?.restaurant_name : (isDish || isGrocery) ? data?.name : ""}
          </p>
          {isGrocery && data?.store?.restaurant_name && (
            <p className="text-xs text-gray-500 truncate">
              from {data.store.restaurant_name}
            </p>
          )}
        </div>

        {/* Rating Section */}
        <div className="flex items-center text-sm gap-3 mt-1">
          {rating > 0 && (
            <div className="flex items-center gap-1.5 bg-brand-50 px-2 py-0.5 rounded-full">
              <div className="flex w-[14px] h-[14px] items-center text-primary justify-center">
                <Icons.Star />
              </div>
              <span className="font-bold text-gray-900">
                {rating}
              </span>
              <span className="text-gray-500 text-[10px]">
                ({isDish ? (data?.order_count || 0) : (data?.rating_count || 0)})
              </span>
            </div>
          )}

          {isRestaurant && (
            <div className="flex items-center gap-1.5 text-gray-600">
              <div className="flex items-center text-primary w-[14px] h-[14px]">
                <Icons.Clock />
              </div>
              <span className="text-[11px]">
                {data?.average_preparing_time
                  ? `${data.average_preparing_time} mins`
                  : "N/A"}
              </span>
            </div>
          )}
        </div>

        <div className="mt-2">
          {isRestaurant ? (
            <span className="text-[#9c9595] text-xs line-clamp-2">
              {Array.isArray(data?.category)
                ? data?.category?.map((cat: any) => cat?.category_name).join(", ")
                : ""}
            </span>
          ) : isDish ? (
            <span className="text-[#9c9595] text-xs line-clamp-2">
              {typeof data?.description === 'string' ? data.description : ""}
            </span>
          ) : isGrocery ? (
            <div className="flex flex-col gap-0.5">
              <span className="text-primary font-bold text-sm">
                {typeof data?.quantity === 'object' ? data.quantity?.title : data?.quantity} {data?.unit}
              </span>
              <span className="text-[#9c9595] text-xs line-clamp-1">
                {typeof data?.description === 'string'
                  ? data.description.replace(/<[^>]*>?/gm, '')
                  : ""}
              </span>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
};

const Favourite = () => {
  const [list, setList] = useState<any[]>([]);
  const [filter, setFilter] = useState<string>("restaurant");
  const [loading, setLoading] = useState(false);
  const [pageNumber, setPageNumber] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [parentCategories, setParentCategories] = useState<any[]>([]);
  const limit = 9;

  useEffect(() => {
    const fetchParentCategories = async () => {
      try {
        const response = await apis.ParentCategory.getParnetCategory();
        const categories = response?.data || [];
        const filtered = categories.filter(
          (cat: any) =>
            cat.slug?.toLowerCase() !== "food" &&
            cat.type?.toLowerCase() !== "food" &&
            cat.name?.toLowerCase() !== "food"
        );
        setParentCategories(filtered);
      } catch (error) {
        console.error("Error fetching categories:", error);
      }
    };
    fetchParentCategories();
  }, []);

  const fetchFavourites = async () => {
    try {
      setLoading(true);
      const type = filter === "restaurant" ? "restaurant" : filter === "dishes" ? "food_item" : filter;
      const query = `page=${pageNumber}&limit=${limit}&type=${type}`;
      const apiRes = await apis.Favourite.getList(query);
      setList(apiRes?.data || []);
      setTotalPages(Math.ceil((apiRes?.count || 1) / limit));
    } catch (error) {
      console.error("Failed to fetch favourites:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleFavourite = async (
    id: string,
    isFav: boolean,
    type: string
  ) => {
    try {
      const payload = {
        status: isFav ? "dislike" : "favourite",
        ...(type === "restaurant"
          ? { restaurant_id: id }
          : type === "dishes"
            ? { food_item_id: id }
            : { grocery_item_id: id }),
      };

      await apis.Favourite.toggle(payload);
      fetchFavourites();
    } catch (error) {
      console.error("Failed to toggle favourite:", error);
    }
  };

  useEffect(() => {
    setPageNumber(1);
  }, [filter]);

  useEffect(() => {
    fetchFavourites();
  }, [filter, pageNumber]);

  const getPaginationRange = () => {
    const start = Math.floor((pageNumber - 1) / 3) * 3 + 1;
    const end = Math.min(start + 2, totalPages);
    return { start, end };
  };

  const { start, end } = getPaginationRange();

  return (

    <div className="flex flex-col min-h-screen p-5 max-w-7xl mx-auto">
      <div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
        <h2 className="text-3xl font-bold text-gray-900 tracking-tight">Favourites</h2>

        {/* Toggle Tabs */}
        <div className="bg-white p-1 rounded-xl shadow-sm border border-gray-100 inline-flex flex-wrap gap-1">
          {[
            { key: "restaurant", label: "Restaurants" },
            { key: "dishes", label: "Dishes" },
            ...parentCategories.map((cat: any) => ({
              key: cat.type,
              label: (cat.name || cat.type).replace(/_/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase())
            }))
          ].map((item) => (
            <button
              key={item.key}
              onClick={() => setFilter(item.key)}
              className={`px-6 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${filter === item.key
                ? "bg-primary text-white shadow-md transform scale-105"
                : "text-gray-500 hover:text-gray-700 hover:bg-gray-50"
                }`}
            >
              {item.label}
            </button>
          ))}
        </div>
      </div>

      {/* Data Grid */}
      {loading ? (
        <div className="text-center py-6 text-gray-500">Loading...</div>
      ) : list?.length > 0 ? (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {list.map((item) => (
              <FavouriteCard
                key={item._id}
                data={item}
                type={filter}
                onFavourite={handleFavourite}
              />
            ))}
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="pagination-container">
              <Pagination>
                <PaginationPrevious
                  onClick={() =>
                    setPageNumber((prev) => Math.max(prev - 1, 1))
                  }
                  className="pagination-btn"
                />
                <PaginationContent>
                  {[...Array(end - start + 1)].map((_, index) => (
                    <PaginationItem key={index}>
                      <PaginationLink
                        isActive={pageNumber === start + index}
                        onClick={() => setPageNumber(start + index)}
                        className={
                          pageNumber === start + index
                            ? "pagination-link-active"
                            : "pagination-link"
                        }
                      >
                        {start + index}
                      </PaginationLink>
                    </PaginationItem>
                  ))}
                  {end < totalPages && (
                    <PaginationEllipsis>
                      <span>...</span>
                    </PaginationEllipsis>
                  )}
                </PaginationContent>
                <PaginationNext
                  onClick={() =>
                    setPageNumber((prev) => Math.min(prev + 1, totalPages))
                  }
                  className="pagination-btn"
                />
              </Pagination>
            </div>
          )}
        </>
      ) : (
        <div className="w-full text-center text-gray-400 py-10">
          <p className="text-lg font-semibold">
            No Favourite {
              filter === "restaurant" ? "Restaurants" :
              filter === "dishes" ? "Dishes" :
              ((parentCategories.find(c => c.type === filter)?.name ||
                (filter.charAt(0).toUpperCase() + filter.slice(1))) + " Items")
            }
          </p>
          <p className="text-sm">
            You haven't added any{" "}
            {
              filter === "restaurant" ? "restaurants" :
              filter === "dishes" ? "dishes" :
              ((parentCategories.find(c => c.type === filter)?.name || filter).toLowerCase() + " items")
            } yet.
          </p>
        </div>
      )}
    </div>
  );
};

export default function FavouritePage() {
  return (
    <DashboardLayout>
      <Favourite />
    </DashboardLayout>
  );
}
