Files
salar-store/components/ProductTabs.tsx
T

173 lines
5.9 KiB
TypeScript

"use client";
import { useEffect, useState, type FormEvent } from "react";
import type { ApiComment } from "@/lib/api";
import { formatDate } from "@/lib/format";
import { SITE } from "@/lib/site";
import { RichContent } from "./RichContent";
type Props = {
productId: string;
descriptionHtml?: string | null;
comments: ApiComment[];
};
type Tab = {
id: "description" | "comments";
fa: string;
en: string;
};
const tabs: Tab[] = [
{ id: "description", fa: "توضیحات محصول", en: "Description" },
{ id: "comments", fa: "نظرات", en: "Comments" },
];
function readToken() {
if (typeof window === "undefined") return "";
return (
window.localStorage.getItem("accessToken") ||
window.localStorage.getItem("meshkee_access_token") ||
""
);
}
export function ProductTabs({ productId, descriptionHtml, comments: initialComments }: Props) {
const [tab, setTab] = useState<"description" | "comments">("description");
const [comments, setComments] = useState(initialComments);
const [sent, setSent] = useState(false);
const [sending, setSending] = useState(false);
const [loggedIn, setLoggedIn] = useState(false);
const authorName = "کاربر";
useEffect(() => {
setLoggedIn(Boolean(readToken()));
}, []);
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!loggedIn) return;
const form = event.currentTarget;
const text = String(new FormData(form).get("text") || "").trim();
if (!text) return;
setSending(true);
try {
const response = await fetch("/api/comments", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
entityType: "product",
entityId: productId,
authorName,
text,
}),
});
if (response.ok) {
setSent(true);
form.reset();
setComments((current) => [
{
id: `local-${Date.now()}`,
authorName,
text,
createdAt: new Date().toISOString(),
},
...current,
]);
}
} finally {
setSending(false);
}
}
return (
<div className="mt-10 rounded-2xl border border-black/5">
<div className="flex justify-center gap-5 border-b border-black/5">
{tabs.map((item) => {
const active = tab === item.id;
const label = item.id === "comments" && comments.length
? `${item.fa} (${comments.length.toLocaleString("fa-IR")})`
: item.fa;
return (
<button
key={item.id}
type="button"
onClick={() => setTab(item.id)}
className={`px-2 py-3 text-center ${
active ? "border-b-2 border-brand text-brand" : "text-zinc-500"
}`}
>
<span className={`block text-base leading-none ${active ? "font-bold" : ""}`}>{label}</span>
<span dir="ltr" className="mt-0.5 block font-oswald text-[9px] font-normal leading-none tracking-[0.16em] uppercase opacity-70">
{item.en}
</span>
</button>
);
})}
</div>
<div className="p-5 md:p-8">
{tab === "description" ? (
descriptionHtml ? (
<RichContent html={descriptionHtml} />
) : (
<p className="text-sm text-zinc-500">توضیحی برای این محصول ثبت نشده است.</p>
)
) : (
<div className="space-y-6">
<div className="space-y-4">
{comments.length ? (
comments.map((comment) => (
<article key={comment.id} className="rounded-xl bg-zinc-50 p-4">
<div className="mb-2 flex items-center justify-between gap-3 text-xs text-zinc-400">
<span className="font-bold text-ink">{comment.authorName || "کاربر"}</span>
{comment.createdAt ? <time>{formatDate(comment.createdAt)}</time> : null}
</div>
<p className="text-sm leading-7 text-zinc-600">{comment.text}</p>
</article>
))
) : (
<p className="text-sm text-zinc-500">هنوز نظری ثبت نشده است.</p>
)}
</div>
{loggedIn ? (
<form onSubmit={onSubmit} className="rounded-xl border border-black/5 p-4">
{sent ? (
<p className="text-sm leading-7 text-zinc-600">نظر شما ثبت شد و پس از تایید نمایش داده می‌شود.</p>
) : (
<div className="flex gap-3">
<input
required
name="text"
placeholder="نظر خود را بنویسید..."
className="min-w-0 flex-1 rounded-xl border border-black/5 bg-zinc-50 px-4 py-2.5 text-sm outline-none focus:border-brand"
/>
<button
type="submit"
disabled={sending}
className="shrink-0 rounded-xl bg-brand px-5 py-2.5 text-sm text-white disabled:opacity-60"
>
ارسال
</button>
</div>
)}
</form>
) : (
<div className="rounded-xl bg-zinc-50 px-4 py-5 text-center">
<p className="text-sm text-zinc-600">برای ثبت نظر ابتدا وارد حساب کاربری شوید.</p>
<a
href={SITE.customerUrl}
className="mt-3 inline-block text-sm text-brand"
>
ورود / ثبت نام
</a>
</div>
)}
</div>
)}
</div>
</div>
);
}