"use client"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useTranslations } from "next-intl"; import { useState } from "react"; import { useParams } from "next/navigation"; import { Link } from "@/i18n/routing"; import { apiGet, apiPost } from "@/lib/api/client"; import { useApiError } from "@/lib/use-api-error"; import { useAuthStore } from "@/lib/stores/auth.store"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { notify } from "@/lib/notify"; import { isTicketClosed, TicketStatusBadge, type TicketStatus, } from "@/components/support/ticket-status-badge"; type SupportTicket = { id: string; subject: string; status: TicketStatus; priority: string; updatedAt: string; messageCount: number; }; type SupportTicketDetail = { ticket: SupportTicket & { updatedAt: string }; messages: { id: string; senderKind: string; senderName?: string | null; body: string; createdAt: string; }[]; }; function formatDate(iso: string) { try { return new Date(iso).toLocaleString("fa-IR", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); } catch { return iso; } } export function SupportScreen() { const t = useTranslations("support"); const apiError = useApiError(); const cafeId = useAuthStore((s) => s.user?.cafeId); const [subject, setSubject] = useState(""); const [body, setBody] = useState(""); const qc = useQueryClient(); const { data: tickets = [], isLoading, isError, error, refetch, } = useQuery({ queryKey: ["support", cafeId], queryFn: () => apiGet(`/api/cafes/${cafeId}/support/tickets`), enabled: !!cafeId, }); const create = useMutation({ mutationFn: () => apiPost(`/api/cafes/${cafeId}/support/tickets`, { subject, body, priority: "Normal", }), onSuccess: (detail) => { setSubject(""); setBody(""); qc.setQueryData(["support", cafeId], (prev = []) => { const row: SupportTicket = { id: detail.ticket.id, subject: detail.ticket.subject, status: detail.ticket.status, priority: detail.ticket.priority, updatedAt: detail.ticket.updatedAt, messageCount: detail.messages.length, }; if (prev.some((x) => x.id === row.id)) return prev; return [row, ...prev]; }); void qc.invalidateQueries({ queryKey: ["support", cafeId] }); notify.success(t("created")); }, onError: () => notify.error(t("createFailed")), }); if (!cafeId) return null; return (

{t("title")}

{t("subtitle")}

{t("newTicket")} setSubject(e.target.value)} placeholder={t("subject")} />