"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Menu, Heart, Truck, ShoppingCart, Info } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useCategories, useFavorites, useOrders } from "@/lib/hooks";
import { useCartCount } from "@/features/cart/hooks/useCart";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";

interface MobileBottomNavProps {
  locale?: string;
  translations?: {
    catalog: string;
    favorites: string;
    orders: string;
    cart: string;
    login: string;
    profile: string;
  };
  onLoginClick?: () => void;
}

export default function MobileBottomNav({
  locale = "ru",
  translations,
  onLoginClick,
}: MobileBottomNavProps) {
  const [isClient, setIsClient] = useState(false);
  const [isCategoryOpen, setIsCategoryOpen] = useState(false);
  const [expandedCategories, setExpandedCategories] = useState<Set<number>>(
    new Set(),
  );
  const [touchStart, setTouchStart] = useState<number | null>(null);
  const t = useTranslations();

  const handleTouchStart = (e: React.TouchEvent) => {
    setTouchStart(e.targetTouches[0].clientX);
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (touchStart === null) return;
    const touchEnd = e.changedTouches[0].clientX;
    const distance = touchStart - touchEnd;

    // Side is left, so swiping left (negative delta or positive distance) closes it
    if (distance > 50) {
      setIsCategoryOpen(false);
    }
    setTouchStart(null);
  };

  const toggleCategory = (categoryId: number) => {
    setExpandedCategories((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(categoryId)) {
        newSet.delete(categoryId);
      } else {
        newSet.add(categoryId);
      }
      return newSet;
    });
  };

  const { data: categories = [] } = useCategories();

  const cartCount = useCartCount();

  const { data: favoritesData } = useFavorites();
  const { data: ordersData } = useOrders();
  const router = useRouter();

  useEffect(() => {
    setIsClient(true);
  }, []);

  const handleNavigation = (path: string) => (e: React.MouseEvent) => {
    e.preventDefault();
    router.push(path);
  };

  if (!isClient) return null;

  return (
    <>
      {/* Mobile Bottom Navigation */}
      <div className="fixed bottom-0 left-0 right-0 z-50 bg-white/95 backdrop-blur-md border-t border-gray-200 shadow-xl lg:hidden">
        <div className="flex items-center justify-around h-16 px-2">
          {/* Catalog Button */}
          <Button
            variant="ghost"
            size="sm"
            className="flex-col gap-0.5 h-auto px-2 py-2 hover:bg-gray-100 rounded-xl transition-colors"
            onClick={() => {
              setIsCategoryOpen(true);
            }}
          >
            <Menu className="h-5 w-5 text-gray-700" />
            <span className="text-xs text-gray-700 font-medium">
              {t("common.catalog")}
            </span>
          </Button>

          {/* Favorites Button */}
          <Button
            variant="ghost"
            size="sm"
            className="relative flex-col gap-0.5 h-auto px-2 py-2 hover:bg-gray-100 rounded-xl transition-colors"
            onClick={handleNavigation("/favorites")}
          >
            <div className="relative">
              <Heart className="h-5 w-5 text-gray-700" />
              {(favoritesData?.length || 0) > 0 && (
                <Badge className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px] bg-gray-900 hover:bg-gray-900 text-white border-2 border-white font-bold">
                  {favoritesData?.length}
                </Badge>
              )}
            </div>
            <span className="text-xs text-gray-700 font-medium">
              {t("common.favorites")}
            </span>
          </Button>

          {/* Orders Button */}
          <Button
            variant="ghost"
            size="sm"
            className="relative flex-col gap-0.5 h-auto px-2 py-2 hover:bg-gray-100 rounded-xl transition-colors"
            onClick={handleNavigation("/orders")}
          >
            <div className="relative">
              <Truck className="h-5 w-5 text-gray-700" />
              {(ordersData?.length || 0) > 0 && (
                <Badge className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px] bg-gray-900 hover:bg-gray-900 text-white border-2 border-white font-bold">
                  {ordersData?.length}
                </Badge>
              )}
            </div>
            <span className="text-xs text-gray-700 font-medium">
              {t("common.orders")}
            </span>
          </Button>

          {/* Cart Button */}
          <Button
            variant="ghost"
            size="sm"
            className="relative flex-col gap-0.5 h-auto px-2 py-2 hover:bg-gray-100 rounded-xl transition-colors"
            onClick={handleNavigation("/cart")}
          >
            <div className="relative">
              <ShoppingCart className="h-5 w-5 text-gray-700" />
              {cartCount > 0 && (
                <Badge className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px] bg-gray-900 hover:bg-gray-900 text-white border-2 border-white font-bold">
                  {cartCount}
                </Badge>
              )}
            </div>
            <span className="text-xs text-gray-700 font-medium">
              {t("common.cart")}
            </span>
          </Button>

          {/* Info Button */}
          <Button
            variant="ghost"
            size="sm"
            className="flex-col gap-0.5 h-auto px-2 py-2 hover:bg-gray-100 rounded-xl transition-colors"
            onClick={() => router.push(`/${locale}/info`)}
          >
            <Info className="h-5 w-5 text-gray-700" />
            <span className="text-xs text-gray-700 font-medium">
              {t("common.info")}
            </span>
          </Button>
        </div>
      </div>

      {/* Category Sheet/Drawer */}
      <Sheet open={isCategoryOpen} onOpenChange={setIsCategoryOpen}>
        <SheetContent
          side="left"
          className="w-[300px] p-0 rounded-none border-r-2 border-gray-200"
          onTouchStart={handleTouchStart}
          onTouchEnd={handleTouchEnd}
        >
          <SheetHeader className="p-6 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-white">
            <SheetTitle className="text-xl font-bold text-gray-900">
              {t("common.catalog")}
            </SheetTitle>
          </SheetHeader>
          <ScrollArea className="h-[calc(100vh-88px)]">
            <div className="p-4">
              {categories.map((category) => (
                <div key={category.id} className="mb-1">
                  <div className="flex items-center">
                    <Link
                      href={`/category/${category.slug}?category_id=${category.id}`}
                      onClick={() => setIsCategoryOpen(false)}
                      className="flex-1 flex items-center gap-2 px-3 py-2 rounded-xl hover:bg-gray-100 transition-all font-bold text-gray-900 hover:text-gray-700"
                    >
                      <span>{category.name}</span>
                    </Link>

                    {/* Toggle button if has children */}
                    {category.children && category.children.length > 0 && (
                      <button
                        onClick={() => toggleCategory(category.id)}
                        className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                      >
                        <svg
                          className={`w-4 h-4 text-gray-600 transition-transform ${
                            expandedCategories.has(category.id)
                              ? "rotate-180"
                              : ""
                          }`}
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M19 9l-7 7-7-7"
                          />
                        </svg>
                      </button>
                    )}
                  </div>

                  {/* Subcategories */}
                  {category.children &&
                    category.children.length > 0 &&
                    expandedCategories.has(category.id) && (
                      <div className="ml-6 mt-1 space-y-0.5">
                        {category.children.map((child: any) => (
                          <Link
                            key={child.id}
                            href={`/category/${child.slug}?category_id=${child.id}`}
                            onClick={() => setIsCategoryOpen(false)}
                            className="block px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-50 rounded-lg transition-all font-medium"
                          >
                            {child.name}
                          </Link>
                        ))}
                      </div>
                    )}
                </div>
              ))}
            </div>
          </ScrollArea>
        </SheetContent>
      </Sheet>
    </>
  );
}
