import { Fragment, useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { Paperclip, Send, UserRound, X } from 'lucide-react';
import {
sendMessage,
useHistory,
useMe,
useMessages,
useTraineeHistory,
} from '../../api/queries';
import type { HistorySession, Message } from '../../api/types';
import MessageAttachmentCard from '../../components/MessageAttachmentCard';
import { displayName, fmtDate, fmtDateTime } from '../../lib/format';
import {
BackButton,
Button,
Card,
ErrorText,
Field,
Modal,
PageHeader,
Select,
Skeleton,
Textarea,
} from '../../components/ui';
import { useToast } from '../../components/toast';
import { useTopbar } from '../../topbar';
import { Avatar } from '../../components/Avatar';
import { ThreadContextCard } from './ThreadContextCard';
/* Bąbelek wiadomości: treść + załącznik + czas (mine = prawo, other = lewo). */
function MessageBubble({
message,
mine,
onOpenSession,
}: {
message: Message;
mine: boolean;
onOpenSession: (sessionId: string) => void;
}) {
return (
{message.body}
{message.attachment && (
)}
{fmtDateTime(message.createdAt)}
);
}
/* Pisanie wiadomości: załącznik (opcjonalny) + textarea + „Załącz wynik” / „Wyślij”. */
function ComposerCard({
body,
onBodyChange,
staged,
onRemoveAttachment,
hasSessions,
onAttach,
onSend,
busy,
}: {
body: string;
onBodyChange: (v: string) => void;
staged: { label: string } | null;
onRemoveAttachment: () => void;
hasSessions: boolean;
onAttach: () => void;
onSend: () => void;
busy: boolean;
}) {
return (
{staged && (
)}
);
}
/* Wybór sesji/ćwiczenia do załączenia w wiadomości (załącznik trafia do composera). */
function AttachmentPickerModal({
open,
onClose,
sessions,
sessionId,
onSessionChange,
exerciseId,
onExerciseChange,
onAttach,
busy,
}: {
open: boolean;
onClose: () => void;
sessions: HistorySession[];
sessionId: string;
onSessionChange: (id: string) => void;
exerciseId: string;
onExerciseChange: (id: string) => void;
onAttach: () => void;
busy: boolean;
}) {
const selectedSession = sessions.find((s) => s.id === sessionId);
return (
{sessions.length === 0 && (
Brak ukończonych sesji do załączenia.
)}
{selectedSession && selectedSession.exercises.length > 0 && (
)}
Załącznik pojawi się nad polem wiadomości — treść możesz dopisać później.
);
}
export default function MessageThread() {
const { coachingId = '' } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { push } = useToast();
const { data: meData } = useMe();
const myId = meData?.user.id;
const { data: thread, isLoading, error } = useMessages(coachingId);
/* Trener: mostek do kokpitu treningowego (panel podopiecznego); podopieczny
nie ma panelu trenera — akcja tylko dla roli trainer. */
useTopbar({
title: 'Komunikator',
back: '/messages',
actions:
thread?.role === 'trainer' && thread.other.id
? [{ label: 'Otwórz panel podopiecznego', icon: UserRound, to: `/trainees/${thread.other.id}` }]
: [],
});
const [body, setBody] = useState('');
const [pickerOpen, setPickerOpen] = useState(false);
const [attachSessionId, setAttachSessionId] = useState('');
const [attachExerciseId, setAttachExerciseId] = useState('');
const [staged, setStaged] = useState<{ sessionId: string; exerciseId: string; label: string } | null>(null);
const [busy, setBusy] = useState(false);
const bottomRef = useRef(null);
const role = thread?.role;
// Trener załącza sesje podopiecznego, podopieczny — własne.
const { data: traineeHist } = useTraineeHistory(role === 'trainer' ? (thread?.other.id ?? '') : '');
const { data: myHist } = useHistory();
const sessions = (role === 'trainer' ? (traineeHist?.sessions ?? []) : (myHist?.sessions ?? [])).filter(
(s) => s.status === 'COMPLETED',
);
useEffect(() => {
bottomRef.current?.scrollIntoView?.({ block: 'end' });
}, [thread?.messages.length]);
const openSession = (sessionId: string) => {
if (role === 'trainer') navigate(`/trainees/${thread?.other.id}?session=${sessionId}`);
else navigate(`/profile/history?session=${sessionId}`);
};
const doSend = async () => {
const text = body.trim();
if (!text) return;
setBusy(true);
try {
await sendMessage(
coachingId,
text,
staged
? {
sessionId: staged.sessionId,
...(staged.exerciseId ? { sessionExerciseId: staged.exerciseId } : {}),
}
: undefined,
);
setBody('');
setStaged(null);
setAttachSessionId('');
setAttachExerciseId('');
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['conversations'] }),
queryClient.invalidateQueries({ queryKey: ['messages', coachingId] }),
]);
} catch (e) {
push((e as Error).message, 'error');
} finally {
setBusy(false);
}
};
/* Załącznik można dodać przed napisaniem treści — trafia do composera jako etap. */
const stageAttachment = () => {
const session = sessions.find((s) => s.id === attachSessionId);
if (!session) return;
const exerciseName = attachExerciseId
? session.exercises.find((e) => e.id === attachExerciseId)?.name
: null;
setStaged({
sessionId: attachSessionId,
exerciseId: attachExerciseId,
label: `${session.date ? fmtDate(session.date) : '—'} · ${session.plan}${exerciseName ? ` · ${exerciseName}` : ''}`,
});
setPickerOpen(false);
};
if (isLoading) {
return (
);
}
const otherName = thread ? displayName(thread.other) : '—';
return (
<>
: undefined}
actions={ navigate('/messages')} />}
/>
{!error && thread && }
{error && Błąd: {(error as Error).message}}
{!error && (thread?.messages.length ?? 0) === 0 && (
Brak wiadomości — napisz pierwszą.
)}
{!error && (
{thread?.messages.map((m, i, arr) => {
const prev = i > 0 ? arr[i - 1] : null;
const newDay = !prev || fmtDate(prev.createdAt) !== fmtDate(m.createdAt);
return (
{newDay && (
{fmtDate(m.createdAt)}
)}
);
})}
)}
setStaged(null)}
hasSessions={sessions.length > 0}
onAttach={() => {
setAttachSessionId(staged?.sessionId ?? '');
setAttachExerciseId(staged?.exerciseId ?? '');
setPickerOpen(true);
}}
onSend={() => void doSend()}
busy={busy}
/>
setPickerOpen(false)}
sessions={sessions}
sessionId={attachSessionId}
onSessionChange={(id) => {
setAttachSessionId(id);
setAttachExerciseId('');
}}
exerciseId={attachExerciseId}
onExerciseChange={setAttachExerciseId}
onAttach={stageAttachment}
busy={busy}
/>
>
);
}