first commit
This commit is contained in:
206
components/layout/ui/ActionButtons.tsx
Normal file
206
components/layout/ui/ActionButtons.tsx
Normal file
@@ -0,0 +1,206 @@
|
||||
"use client";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMemo } from "react";
|
||||
import type React from "react";
|
||||
import Link from "next/link";
|
||||
import { User, Truck, Heart, Store, LogOut } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { useCart, useFavorites, useOrders, useCartCount } from "@/lib/hooks";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLogout } from "@/lib/hooks/useAuth";
|
||||
import {
|
||||
CartIcon,
|
||||
FavoriteIcon,
|
||||
OrderIcon,
|
||||
ProfileIcon,
|
||||
} from "@/components/icons";
|
||||
|
||||
interface ActionButtonsProps {
|
||||
isAuthenticated: boolean;
|
||||
onAuthClick: () => void;
|
||||
isLoading?: boolean;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
interface ActionButtonData {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
href?: string;
|
||||
onClick?: () => void;
|
||||
badgeCount?: number;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export default function ActionButtons({
|
||||
isAuthenticated,
|
||||
onAuthClick,
|
||||
isLoading: authLoading,
|
||||
locale = "ru",
|
||||
}: ActionButtonsProps) {
|
||||
const t = useTranslations();
|
||||
const { mutate: logout, isPending: isLoggingOut } = useLogout();
|
||||
const router = useRouter();
|
||||
const { data: cartData, isLoading: cartLoading } = useCart();
|
||||
const { data: favoritesData, isLoading: favoritesLoading } = useFavorites();
|
||||
const { data: ordersData, isLoading: ordersLoading } = useOrders();
|
||||
|
||||
// Calculate cart count from cart items array
|
||||
const cartCount = useCartCount()
|
||||
|
||||
// Calculate favorites count
|
||||
const favoritesCount = useMemo(() => {
|
||||
if (!favoritesData) return 0;
|
||||
return Array.isArray(favoritesData) ? favoritesData.length : 0;
|
||||
}, [favoritesData]);
|
||||
|
||||
// Calculate orders count
|
||||
const ordersCount = useMemo(() => {
|
||||
if (!ordersData) return 0;
|
||||
return Array.isArray(ordersData) ? ordersData.length : 0;
|
||||
}, [ordersData]);
|
||||
|
||||
const handleLogout = () => {
|
||||
logout(undefined, {
|
||||
onSuccess: () => {
|
||||
router.push(`/${locale}`);
|
||||
router.refresh();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const buttons: ActionButtonData[] = useMemo(
|
||||
() => [
|
||||
{
|
||||
icon: <Store />,
|
||||
label: t("common.openStore"),
|
||||
href: "/openStore",
|
||||
},
|
||||
{
|
||||
icon: <OrderIcon />,
|
||||
label: t("common.orders"),
|
||||
href: "/orders",
|
||||
badgeCount: ordersCount,
|
||||
isLoading: ordersLoading,
|
||||
},
|
||||
{
|
||||
icon: <FavoriteIcon />,
|
||||
label: t("common.favorites"),
|
||||
href: "/favorites",
|
||||
badgeCount: favoritesCount,
|
||||
isLoading: favoritesLoading,
|
||||
},
|
||||
{
|
||||
icon: <CartIcon />,
|
||||
label: t("common.cart"),
|
||||
href: "/cart",
|
||||
badgeCount: cartCount,
|
||||
isLoading: cartLoading,
|
||||
},
|
||||
],
|
||||
[
|
||||
ordersCount,
|
||||
ordersLoading,
|
||||
favoritesCount,
|
||||
favoritesLoading,
|
||||
cartCount,
|
||||
cartLoading,
|
||||
t,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="hidden items-center gap-1 lg:flex">
|
||||
{/* Profile/Login Button with Dropdown */}
|
||||
{authLoading ? (
|
||||
<div className="h-10 w-24 animate-pulse bg-gray-200 rounded" />
|
||||
) : isAuthenticated ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-col cursor-pointer gap-0.5 h-auto px-2 py-2"
|
||||
>
|
||||
<ProfileIcon />
|
||||
<span className="text-xs text-gray-700">{t("profile")}</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => router.push(`/${locale}/me`)}>
|
||||
<User className="mr-2 h-4 w-4" />
|
||||
{t("profile")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleLogout} disabled={isLoggingOut}>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
{isLoggingOut ? t("logging_out") : t("common.logout")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex-col cursor-pointer gap-0.5 h-auto px-2 py-2"
|
||||
onClick={onAuthClick}
|
||||
>
|
||||
<ProfileIcon />
|
||||
<span className="text-xs text-gray-700">{t("common.login")}</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Other Action Buttons */}
|
||||
{buttons.map((button, index) => (
|
||||
<ActionButton key={index} {...button} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButton({
|
||||
icon,
|
||||
label,
|
||||
href,
|
||||
onClick,
|
||||
badgeCount,
|
||||
isLoading,
|
||||
}: ActionButtonData) {
|
||||
const buttonContent = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="relative flex-col gap-0.5 h-auto px-2 py-2"
|
||||
onClick={onClick}
|
||||
>
|
||||
<div className="relative">
|
||||
{icon}
|
||||
{badgeCount !== undefined && badgeCount > 0 && (
|
||||
<Badge
|
||||
variant="destructive"
|
||||
className="absolute -right-2 -top-2 h-4 w-4 flex items-center justify-center p-0 text-[10px]"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Skeleton className="h-3 w-3 rounded-full" />
|
||||
) : (
|
||||
badgeCount
|
||||
)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-gray-700">{label}</span>
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (href) {
|
||||
return <Link href={href}>{buttonContent}</Link>;
|
||||
}
|
||||
|
||||
return buttonContent;
|
||||
}
|
||||
197
components/layout/ui/AuthDialog.tsx
Normal file
197
components/layout/ui/AuthDialog.tsx
Normal file
@@ -0,0 +1,197 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback } from "react";
|
||||
import Image from "next/image";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { toast } from "sonner";
|
||||
import Logo from "@/public/logo.webp";
|
||||
import { useLogin, useVerifyToken } from "@/lib/hooks/useAuth";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
interface AuthDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function AuthDialog({ isOpen, onClose }: AuthDialogProps) {
|
||||
const [phone, setPhone] = useState("+993 ");
|
||||
const [otp, setOtp] = useState("");
|
||||
const [otpSent, setOtpSent] = useState(false);
|
||||
const t = useTranslations();
|
||||
|
||||
const { mutate: login, isPending: isLoginLoading } = useLogin();
|
||||
const { mutate: verifyToken, isPending: isVerifyLoading } = useVerifyToken();
|
||||
|
||||
const resetDialog = useCallback(() => {
|
||||
setOtpSent(false);
|
||||
setPhone("+993 ");
|
||||
setOtp("");
|
||||
onClose();
|
||||
}, [onClose]);
|
||||
|
||||
const formatPhoneForBackend = (phoneNumber: string): string => {
|
||||
return phoneNumber.replace(/^\+993\s*/, "").replace(/\s+/g, "");
|
||||
};
|
||||
|
||||
const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const input = e.target.value;
|
||||
const prefix = "+993 ";
|
||||
|
||||
if (input.length < prefix.length) {
|
||||
setPhone(prefix);
|
||||
return;
|
||||
}
|
||||
|
||||
const digitsOnly = input.substring(prefix.length).replace(/\D/g, "");
|
||||
|
||||
const limitedDigits = digitsOnly.substring(0, 8);
|
||||
|
||||
let formattedPhone = prefix;
|
||||
if (limitedDigits.length > 0) {
|
||||
formattedPhone += limitedDigits.substring(0, 2);
|
||||
|
||||
if (limitedDigits.length > 2) {
|
||||
formattedPhone += " " + limitedDigits.substring(2);
|
||||
}
|
||||
}
|
||||
|
||||
setPhone(formattedPhone);
|
||||
};
|
||||
|
||||
const isPhoneValid = (): boolean => {
|
||||
const phoneDigits = formatPhoneForBackend(phone);
|
||||
return phoneDigits.length === 8;
|
||||
};
|
||||
|
||||
const handleSendOtp = useCallback(() => {
|
||||
if (!isPhoneValid()) {
|
||||
toast.error(t("invalid_phone"));
|
||||
return;
|
||||
}
|
||||
|
||||
const phoneNumber = formatPhoneForBackend(phone);
|
||||
|
||||
login(
|
||||
{ phone_number: parseInt(phoneNumber, 10) },
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(t("code_sent"));
|
||||
setOtpSent(true);
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error?.response?.data?.message || t("error_occurred"));
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [phone, login, t]);
|
||||
|
||||
const handleLogin = useCallback(() => {
|
||||
if (otp.length < 4) {
|
||||
toast.error(t("invalid_code"));
|
||||
return;
|
||||
}
|
||||
|
||||
const phoneNumber = formatPhoneForBackend(phone);
|
||||
|
||||
verifyToken(
|
||||
{
|
||||
phone_number: parseInt(phoneNumber, 10),
|
||||
code: parseInt(otp, 10),
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(t("login_success"));
|
||||
resetDialog();
|
||||
window.location.reload();
|
||||
},
|
||||
onError: (error: any) => {
|
||||
toast.error(error?.response?.data?.message || t("wrong_code"));
|
||||
},
|
||||
}
|
||||
);
|
||||
}, [otp, phone, verifyToken, resetDialog, t]);
|
||||
|
||||
const handleKeyPress = useCallback(
|
||||
(e: React.KeyboardEvent, action: () => void) => {
|
||||
if (e.key === "Enter") {
|
||||
action();
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={resetDialog}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center justify-center mb-4">
|
||||
<div className="relative h-8 w-[180px]">
|
||||
<Image src={Logo} alt="Logo" fill className="object-contain" />
|
||||
</div>
|
||||
</div>
|
||||
<DialogTitle className="text-2xl text-center">
|
||||
{t("common.enterPhone")}
|
||||
</DialogTitle>
|
||||
<p className="text-center text-sm text-gray-600">
|
||||
{t("common.weWillSendCode")}
|
||||
</p>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 mt-4">
|
||||
<div>
|
||||
<Input
|
||||
type="tel"
|
||||
placeholder="+993 61 097651"
|
||||
value={phone}
|
||||
onChange={handlePhoneChange}
|
||||
className="h-12 rounded-xl"
|
||||
onKeyDown={(e) => handleKeyPress(e, handleSendOtp)}
|
||||
disabled={otpSent || isLoginLoading}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">{t("phone_format")}</p>
|
||||
</div>
|
||||
|
||||
{otpSent && (
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={t("common.code")}
|
||||
value={otp}
|
||||
onChange={(e) =>
|
||||
setOtp(e.target.value.replace(/\D/g, "").substring(0, 6))
|
||||
}
|
||||
className="h-12 rounded-xl"
|
||||
onKeyDown={(e) => handleKeyPress(e, handleLogin)}
|
||||
disabled={isVerifyLoading}
|
||||
autoFocus
|
||||
maxLength={6}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Button
|
||||
onClick={otpSent ? handleLogin : handleSendOtp}
|
||||
className="w-full cursor-pointer h-12 rounded-xl font-bold text-base bg-[#005bff] hover:bg-[#0041c4]"
|
||||
size="lg"
|
||||
disabled={
|
||||
isLoginLoading || isVerifyLoading || (!otpSent && !isPhoneValid())
|
||||
}
|
||||
>
|
||||
{isLoginLoading
|
||||
? t("sending")
|
||||
: isVerifyLoading
|
||||
? t("verifying")
|
||||
: otpSent
|
||||
? t("verify")
|
||||
: t("common.send")}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
164
components/layout/ui/CategoryMenu.tsx
Normal file
164
components/layout/ui/CategoryMenu.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
// CategoryMenu.tsx
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import Link from "next/link";
|
||||
import { useCategories } from "@/lib/hooks";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
|
||||
interface CategoryMenuProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function CategoryMenu({ isOpen, onClose }: CategoryMenuProps) {
|
||||
const [hoveredCategory, setHoveredCategory] = useState<number | null>(null);
|
||||
const { data: categories, isLoading } = useCategories();
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Click outside to close
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement;
|
||||
|
||||
|
||||
if (target.closest("[data-catalog-trigger]")) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (menuRef.current && !menuRef.current.contains(target)) {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
// Add listener after a small delay to prevent immediate closing
|
||||
const timeoutId = setTimeout(() => {
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
}, 100);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeoutId);
|
||||
document.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
// ESC key to close
|
||||
useEffect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
const handleEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("keydown", handleEscape);
|
||||
return () => document.removeEventListener("keydown", handleEscape);
|
||||
}, [isOpen, onClose]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
const categoryList = categories || [];
|
||||
const activeCategory =
|
||||
hoveredCategory !== null ? categoryList[hoveredCategory] : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="fixed inset-0 bg-black/20 z-30" onClick={onClose} />
|
||||
|
||||
{/* Menu */}
|
||||
<div
|
||||
ref={menuRef}
|
||||
className="fixed left-0 right-0 top-16 z-40 bg-white border-b rounded-b-lg shadow-lg max-w-[1504px] mx-auto"
|
||||
>
|
||||
<div className="mx-auto px-4">
|
||||
<div className="flex">
|
||||
<CategoryList
|
||||
categories={categoryList}
|
||||
isLoading={isLoading}
|
||||
onCategoryHover={setHoveredCategory}
|
||||
onCategoryClick={onClose}
|
||||
/>
|
||||
|
||||
{activeCategory?.children && (
|
||||
<SubcategoryList
|
||||
category={activeCategory}
|
||||
onSubcategoryClick={onClose}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface CategoryListProps {
|
||||
categories: any[];
|
||||
isLoading: boolean;
|
||||
onCategoryHover: (index: number) => void;
|
||||
onCategoryClick: () => void;
|
||||
}
|
||||
|
||||
function CategoryList({
|
||||
categories,
|
||||
isLoading,
|
||||
onCategoryHover,
|
||||
onCategoryClick,
|
||||
}: CategoryListProps) {
|
||||
return (
|
||||
<div className="w-[280px] border-r">
|
||||
<div className="max-h-[calc(100vh-4rem)] overflow-y-auto py-2">
|
||||
{isLoading
|
||||
? [1, 2, 3, 4, 5].map((i) => (
|
||||
<Skeleton key={i} className="h-10 mx-4 my-2 rounded" />
|
||||
))
|
||||
: categories.map((category, index) => (
|
||||
<Link
|
||||
key={category.id}
|
||||
href={`/category/${category.slug}?category_id=${category.id}`}
|
||||
onClick={onCategoryClick}
|
||||
onMouseEnter={() => onCategoryHover(index)}
|
||||
className="flex items-center gap-3 px-4 py-3 rounded-lg hover:bg-gray-100 hover:text-primary transition-colors"
|
||||
>
|
||||
{category.icon_class && (
|
||||
<i className={`${category.icon_class} text-xl`} />
|
||||
)}
|
||||
<span>{category.name}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SubcategoryListProps {
|
||||
category: any;
|
||||
onSubcategoryClick: () => void;
|
||||
}
|
||||
|
||||
function SubcategoryList({
|
||||
category,
|
||||
onSubcategoryClick,
|
||||
}: SubcategoryListProps) {
|
||||
return (
|
||||
<div className="flex-1 p-6">
|
||||
<h3 className="text-xl font-semibold mb-4">{category.name}</h3>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{category.children?.map((subCategory: any) => (
|
||||
<Link
|
||||
key={subCategory.id}
|
||||
href={`/category/${subCategory.slug}?category_id=${subCategory.id}`}
|
||||
onClick={onSubcategoryClick}
|
||||
className="text-gray-600 hover:text-black text-sm py-1 hover:underline"
|
||||
>
|
||||
{subCategory.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
80
components/layout/ui/LanguageSelector.tsx
Normal file
80
components/layout/ui/LanguageSelector.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
import { useRouter, usePathname } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import { useLocale } from "next-intl";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import tm from "@/public/tm.png";
|
||||
import ru from "@/public/ru.png";
|
||||
|
||||
interface Language {
|
||||
code: string;
|
||||
name: string;
|
||||
flag: any;
|
||||
}
|
||||
|
||||
const LANGUAGES: Language[] = [
|
||||
{ code: "ru", name: "Russian", flag: ru },
|
||||
{ code: "tm", name: "Turkmen", flag: tm },
|
||||
];
|
||||
|
||||
export default function LanguageSelector() {
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const handleLanguageChange = async (newLocale: string) => {
|
||||
if (typeof window !== "undefined") {
|
||||
(window as any).i18n = { language: newLocale };
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries();
|
||||
|
||||
const currentPath = pathname.replace(`/${locale}`, "");
|
||||
router.replace(`/${newLocale}${currentPath}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<Select value={locale} onValueChange={handleLanguageChange}>
|
||||
<SelectTrigger className="w-[70px] md:h-10! flex items-center justify-center rounded-lg border-gray-300">
|
||||
<SelectValue>
|
||||
<FlagIcon locale={locale} />
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{LANGUAGES.map((language) => (
|
||||
<SelectItem key={language.code} value={language.code}>
|
||||
<div className="flex items-center gap-2">
|
||||
<FlagIcon locale={language.code} />
|
||||
<span>{language.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
|
||||
function FlagIcon({ locale }: { locale: string }) {
|
||||
const language = LANGUAGES.find((lang) => lang.code === locale);
|
||||
|
||||
if (!language) return null;
|
||||
|
||||
return (
|
||||
<div className="relative h-5 w-7">
|
||||
<Image
|
||||
src={language.flag || "/placeholder.svg"}
|
||||
alt={language.name}
|
||||
fill
|
||||
className="object-cover rounded"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
167
components/layout/ui/SearchBar.tsx
Normal file
167
components/layout/ui/SearchBar.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import { Search, X, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useSearchProducts } from "@/features/search/hooks/useSearch";
|
||||
import Image from "next/image";
|
||||
import { SearchIcon } from "@/components/icons";
|
||||
|
||||
interface SearchBarProps {
|
||||
isMobile: boolean;
|
||||
searchPlaceholder: string;
|
||||
isOpen?: boolean;
|
||||
onClose?: () => void;
|
||||
className?: string;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
export default function SearchBar({
|
||||
isMobile,
|
||||
searchPlaceholder,
|
||||
isOpen,
|
||||
onClose,
|
||||
className = "",
|
||||
locale = "ru",
|
||||
}: SearchBarProps) {
|
||||
const router = useRouter();
|
||||
const [searchValue, setSearchValue] = useState("");
|
||||
const [debouncedSearch, setDebouncedSearch] = useState("");
|
||||
const [showResults, setShowResults] = useState(false);
|
||||
const searchRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { data, isLoading } = useSearchProducts({ q: debouncedSearch });
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedSearch(searchValue);
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchValue]);
|
||||
|
||||
useEffect(() => {
|
||||
if (debouncedSearch && data?.data && data.data.length > 0) {
|
||||
setShowResults(true);
|
||||
} else {
|
||||
setShowResults(false);
|
||||
}
|
||||
}, [debouncedSearch, data]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
|
||||
setShowResults(false);
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const handleSearch = (value: string) => {
|
||||
setSearchValue(value);
|
||||
};
|
||||
|
||||
const handleProductClick = (productId: number) => {
|
||||
router.push(`/${locale}/product/${productId}`);
|
||||
setSearchValue("");
|
||||
setShowResults(false);
|
||||
if (onClose) onClose();
|
||||
};
|
||||
|
||||
const handleClearSearch = () => {
|
||||
setSearchValue("");
|
||||
setShowResults(false);
|
||||
};
|
||||
|
||||
const SearchResults = () => {
|
||||
if (!showResults || !data?.data) return null;
|
||||
|
||||
return (
|
||||
<div className="absolute top-full left-0 right-0 mt-2 bg-white border rounded-xl shadow-lg max-h-[400px] overflow-y-auto z-50">
|
||||
{data.data.map((product) => (
|
||||
<button
|
||||
key={product.id}
|
||||
onClick={() => handleProductClick(product.id)}
|
||||
className="w-full cursor-pointer flex items-center gap-3 p-3 hover:bg-gray-50 transition-colors border-b last:border-b-0"
|
||||
>
|
||||
<div className="relative w-16 h-16 shrink-0">
|
||||
<Image
|
||||
src={product.thumbnail}
|
||||
alt={product.name}
|
||||
fill
|
||||
className="object-cover rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 text-left">
|
||||
<p className="font-medium text-sm line-clamp-2">{product.name}</p>
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
{product.price_amount} TMT
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">{product.brand.name}</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="top-4 translate-y-0">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{searchPlaceholder}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="relative" ref={searchRef}>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={searchPlaceholder}
|
||||
value={searchValue}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
className="h-10 rounded-xl focus:border-[#005bff] focus-visible:border-[#005bff] focus-visible:ring-0 active:border-[#005bff]"
|
||||
autoFocus
|
||||
/>
|
||||
{isLoading && (
|
||||
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-gray-400" />
|
||||
)}
|
||||
<SearchResults />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`bg-[#005bff] rounded-xl flex items-center relative ${className}`} ref={searchRef}>
|
||||
<div className="w-full relative">
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={searchPlaceholder}
|
||||
value={searchValue}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
className="border-[#005bff] w-full rounded-xl border-2 focus-visible:ring-0 bg-white px-2"
|
||||
/>
|
||||
{isLoading && (
|
||||
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-gray-400" />
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size="icon"
|
||||
className="h-auto hover:bg-[#005bff] cursor-pointer bg-transparent flex items-center mr-1.5 text-white"
|
||||
>
|
||||
<SearchIcon />
|
||||
</Button>
|
||||
<SearchResults />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user