// Path: Frontend/src/components/dashboard/messages/dashboard-messages.sections.tsx

import type { Component } from "solid-js";
import { For, Show } from "solid-js";
import { displayName, formatMessageTimestamp, formatShortTimestamp, getDashboardMessagesInboxData, getMessageThreadDetail, initialsFor, roleLabel, wasMessageEdited, type MessageParticipant } from "./dashboard-messages.data";
import styles from "./dashboard-messages.module.scss";

type InboxData = Awaited<ReturnType<typeof getDashboardMessagesInboxData>>;
type InboxThread = InboxData["threads"][number];
type InboxRecipient = InboxData["recipients"][number];
type ThreadDetail = Awaited<ReturnType<typeof getMessageThreadDetail>>;
type ThreadMessage = ThreadDetail["messages"][number];

export const otherParticipants = (participants: MessageParticipant[], currentUserId: number) => participants.filter((participant) => participant.id !== currentUserId);

export const participantSummary = (participants: MessageParticipant[], currentUserId: number) => {
	const others = otherParticipants(participants, currentUserId);
	if (!others.length) return "Just you";
	return others.map((participant) => `${displayName(participant)} · ${roleLabel(participant.role)}`).join(" • ");
};

type DashboardMessagesMailboxProps = {
	railMode: "inbox" | "compose";
	recipients: InboxRecipient[];
	threads: InboxThread[];
	filteredThreads: InboxThread[];
	selectedThreadId: number | null;
	currentUserId: number;
	searchQuery: string;
	recipientId: string;
	subject: string;
	composeError: string | null;
	composeSuccess: string | null;
	creatingThread: boolean;
	inboxLoading: boolean;
	inboxError: boolean;
	onSetRailMode: (mode: "inbox" | "compose") => void;
	onRecipientInput: (value: string) => void;
	onSubjectInput: (value: string) => void;
	onSearchInput: (value: string) => void;
	onSelectThread: (threadId: number) => void;
	onSubmitNewThread: (event: SubmitEvent) => Promise<void> | void;
};

export const DashboardMessagesMailbox: Component<DashboardMessagesMailboxProps> = (props) => (
	<div class={styles.leftRail}>
		<article class={styles.panel}>
			<div class={styles.railHeader}>
				<div>
					<p class={styles.panelEyebrow}>Mailbox</p>
					<h2>{props.railMode === "inbox" ? "Inbox" : "Start a thread"}</h2>
				</div>
				<div class={styles.railToggle}>
					<button type="button" classList={{ [styles.toggleButton]: true, [styles.toggleButtonActive]: props.railMode === "inbox" }} onClick={() => props.onSetRailMode("inbox")}>
						Inbox
					</button>
					<button type="button" classList={{ [styles.toggleButton]: true, [styles.toggleButtonActive]: props.railMode === "compose" }} onClick={() => props.onSetRailMode("compose")}>
						New thread
					</button>
				</div>
			</div>

			<Show
				when={props.railMode === "inbox"}
				fallback={
					<form class={styles.form} onSubmit={(event) => void props.onSubmitNewThread(event)}>
						<label class={styles.fieldLabel}>
							<span>Contact</span>
							<select class={styles.selectInput} value={props.recipientId} onInput={(event) => props.onRecipientInput(event.currentTarget.value)}>
								<option value="">Choose a contact</option>
								<For each={props.recipients}>
									{(recipient) => (
										<option value={String(recipient.id)}>
											{displayName(recipient)} · {roleLabel(recipient.role)}
										</option>
									)}
								</For>
							</select>
						</label>

						<label class={styles.fieldLabel}>
							<span>Subject</span>
							<input class={styles.textInput} type="text" value={props.subject} placeholder="Homework check-in" onInput={(event) => props.onSubjectInput(event.currentTarget.value)} />
						</label>

						<Show when={props.composeError}>{(message) => <p class={`${styles.feedbackMessage} ${styles.feedbackError}`}>{message()}</p>}</Show>
						<Show when={props.composeSuccess}>{(message) => <p class={`${styles.feedbackMessage} ${styles.feedbackSuccess}`}>{message()}</p>}</Show>

						<p class={styles.composeNote}>The thread opens right away after creation, so you can send the first message from the conversation pane.</p>

						<button class={styles.primaryAction} type="submit" disabled={props.creatingThread || props.recipients.length === 0}>
							{props.creatingThread ? "Starting thread..." : "Start thread"}
						</button>
					</form>
				}
			>
				<div class={styles.inboxTools}>
					<label class={styles.searchField}>
						<span class={styles.searchIcon} aria-hidden="true">
							<svg viewBox="0 0 24 24">
								<circle cx="11" cy="11" r="6" />
								<path d="M20 20l-4.2-4.2" />
							</svg>
						</span>
						<input type="search" value={props.searchQuery} placeholder="Search subjects, contacts, or previews" onInput={(event) => props.onSearchInput(event.currentTarget.value)} />
					</label>
					<p class={styles.resultsNote}>
						{props.filteredThreads.length} of {props.threads.length} thread{props.threads.length === 1 ? "" : "s"}
					</p>
				</div>

				<Show when={!props.inboxLoading} fallback={<div class={styles.emptyState}>Loading your inbox…</div>}>
					<Show when={!props.inboxError} fallback={<div class={styles.emptyState}>We could not load your threads right now.</div>}>
						<Show when={props.threads.length} fallback={<div class={styles.emptyState}>No conversations yet. Use New thread to start one.</div>}>
							<Show when={props.filteredThreads.length} fallback={<div class={styles.emptyState}>No threads match that search yet.</div>}>
								<div class={styles.threadList}>
									<For each={props.filteredThreads}>
										{(thread) => {
											const peers = () => otherParticipants(thread.participants, props.currentUserId);
											return (
												<button type="button" classList={{ [styles.threadButton]: true, [styles.threadButtonActive]: props.selectedThreadId === thread.id }} onClick={() => props.onSelectThread(thread.id)}>
													<div class={styles.threadButtonTop}>
														<div class={styles.senderWrap}>
															<span class={styles.avatar}>{initialsFor(peers()[0] ?? { full_name: thread.subject })}</span>
															<div class={styles.threadCopy}>
																<strong>{thread.subject}</strong>
																<p>{participantSummary(thread.participants, props.currentUserId)}</p>
															</div>
														</div>
														<div class={styles.threadMeta}>
															<small>{formatShortTimestamp(thread.last_message_created_at ?? thread.updated_at)}</small>
															<Show when={thread.unread_count > 0}>
																<span class={styles.unreadBadge}>{thread.unread_count}</span>
															</Show>
														</div>
													</div>
													<p class={styles.preview}>{thread.last_message_body?.trim() || "No messages yet. Open this thread to send the first one."}</p>
												</button>
											);
										}}
									</For>
								</div>
							</Show>
						</Show>
					</Show>
				</Show>
			</Show>
		</article>
	</div>
);

type DashboardMessagesThreadPanelProps = {
	selectedThreadId: number | null;
	threadLoading: boolean;
	threadError: boolean;
	thread: ThreadDetail | null;
	currentUserId: number;
	editingThreadTitle: boolean;
	threadSubjectDraft: string;
	threadActionError: string | null;
	threadActionSuccess: string | null;
	messageActionError: string | null;
	messageActionSuccess: string | null;
	replyBody: string;
	threadCanManage: boolean;
	mailboxCollapsed: boolean;
	markingThreadId: number | null;
	deletingThreadId: number | null;
	savingThreadTitle: boolean;
	editingMessageId: number | null;
	editingMessageBody: string;
	savingMessageId: number | null;
	deletingMessageId: number | null;
	sendingReply: boolean;
	onThreadSubjectDraftInput: (value: string) => void;
	onReplyBodyInput: (value: string) => void;
	onEditingMessageBodyInput: (value: string) => void;
	onToggleMailbox: () => void;
	onBeginEditThreadTitle: () => void;
	onCancelEditThreadTitle: () => void;
	onSubmitThreadTitle: (event: SubmitEvent) => Promise<void> | void;
	onRemoveThread: () => Promise<void> | void;
	onBeginMessageEdit: (messageId: number, body: string) => void;
	onCancelMessageEdit: () => void;
	onSubmitMessageEdit: (event: SubmitEvent, messageId: number) => Promise<void> | void;
	onRemoveMessage: (messageId: number) => Promise<void> | void;
	onSubmitReply: (event: SubmitEvent) => Promise<void> | void;
};

export const DashboardMessagesThreadPanel: Component<DashboardMessagesThreadPanelProps> = (props) => (
	<article class={`${styles.panel} ${styles.threadPanel}`}>
		<Show when={props.selectedThreadId} fallback={<div class={styles.emptyState}>Pick a thread or start a new conversation to open the message panel.</div>}>
			<Show when={!props.threadLoading} fallback={<div class={styles.emptyState}>Loading this conversation…</div>}>
				<Show when={!props.threadError && props.thread} keyed fallback={<div class={styles.emptyState}>We could not load this conversation right now.</div>}>
					{(thread) => (
						<>
							<div class={styles.threadPanelHeader}>
								<div>
									<p class={styles.panelEyebrow}>Conversation</p>
									<Show when={props.editingThreadTitle} fallback={<h2>{thread.subject}</h2>}>
										<form class={styles.inlineEditForm} onSubmit={(event) => void props.onSubmitThreadTitle(event)}>
											<input class={styles.textInput} type="text" value={props.threadSubjectDraft} onInput={(event) => props.onThreadSubjectDraftInput(event.currentTarget.value)} />
											<div class={styles.inlineEditActions}>
												<button class={styles.primaryAction} type="submit" disabled={props.savingThreadTitle}>
													{props.savingThreadTitle ? "Saving..." : "Save title"}
												</button>
												<button class={styles.secondaryAction} type="button" onClick={props.onCancelEditThreadTitle}>
													Cancel
												</button>
											</div>
										</form>
									</Show>
									<p>{participantSummary(thread.participants, props.currentUserId)}</p>
									<Show when={props.threadActionError}>{(message) => <p class={`${styles.feedbackMessage} ${styles.feedbackError}`}>{message()}</p>}</Show>
									<Show when={props.threadActionSuccess}>{(message) => <p class={`${styles.feedbackMessage} ${styles.feedbackSuccess}`}>{message()}</p>}</Show>
								</div>
								<div class={styles.threadHeaderActions}>
									<Show when={props.threadCanManage && !props.editingThreadTitle}>
										<button type="button" class={styles.secondaryAction} onClick={props.onBeginEditThreadTitle}>
											Edit title
										</button>
										<button type="button" class={styles.dangerAction} onClick={() => void props.onRemoveThread()} disabled={props.deletingThreadId === thread.id}>
											{props.deletingThreadId === thread.id ? "Deleting..." : "Delete conversation"}
										</button>
									</Show>
									<button type="button" class={styles.secondaryAction} onClick={props.onToggleMailbox}>
										{props.mailboxCollapsed ? "Show mailbox" : "Collapse mailbox"}
									</button>
									<Show when={props.markingThreadId === thread.id}>
										<span class={styles.statusNote}>Marking as read…</span>
									</Show>
								</div>
							</div>

							<Show when={thread.messages.length} fallback={<div class={styles.emptyThreadState}>No messages yet. Send the first reply below to get this thread moving.</div>}>
								<div class={styles.messageStream}>
									<For each={thread.messages}>
										{(message: ThreadMessage) => (
											<div classList={{ [styles.messageRow]: true, [styles.messageRowMine]: message.mine }}>
												<div classList={{ [styles.messageBubble]: true, [styles.messageBubbleMine]: message.mine }}>
													<div class={styles.messageMeta}>
														<div class={styles.senderWrap}>
															<span class={styles.avatar}>{initialsFor(message.sender)}</span>
															<div>
																<strong>{displayName(message.sender)}</strong>
																<p>{roleLabel(message.sender.role)}</p>
															</div>
														</div>
														<div class={styles.messageMetaAside}>
															<small>{formatMessageTimestamp(message.created_at)}</small>
															<Show when={wasMessageEdited(message.created_at, message.updated_at)}>
																<span class={styles.editedNote}>Edited</span>
															</Show>
														</div>
													</div>
													<Show when={props.editingMessageId === message.id} fallback={<p class={styles.messageBody}>{message.body}</p>}>
														<form class={styles.inlineEditForm} onSubmit={(event) => void props.onSubmitMessageEdit(event, message.id)}>
															<textarea class={styles.textArea} rows={4} value={props.editingMessageBody} onInput={(event) => props.onEditingMessageBodyInput(event.currentTarget.value)} />
															<div class={styles.inlineEditActions}>
																<button class={styles.primaryAction} type="submit" disabled={props.savingMessageId === message.id}>
																	{props.savingMessageId === message.id ? "Saving..." : "Save message"}
																</button>
																<button class={styles.secondaryAction} type="button" onClick={props.onCancelMessageEdit}>
																	Cancel
																</button>
															</div>
														</form>
													</Show>
													<Show when={message.mine && props.editingMessageId !== message.id}>
														<div class={styles.messageActions}>
															<button type="button" class={styles.messageActionButton} onClick={() => props.onBeginMessageEdit(message.id, message.body)}>
																Edit
															</button>
															<button
																type="button"
																class={`${styles.messageActionButton} ${styles.messageActionDanger}`}
																onClick={() => void props.onRemoveMessage(message.id)}
																disabled={props.deletingMessageId === message.id}
															>
																{props.deletingMessageId === message.id ? "Deleting..." : "Delete"}
															</button>
														</div>
													</Show>
												</div>
											</div>
										)}
									</For>
								</div>
							</Show>

							<Show when={props.messageActionError}>{(message) => <p class={`${styles.feedbackMessage} ${styles.feedbackError}`}>{message()}</p>}</Show>
							<Show when={props.messageActionSuccess}>{(message) => <p class={`${styles.feedbackMessage} ${styles.feedbackSuccess}`}>{message()}</p>}</Show>

							<form class={styles.replyForm} onSubmit={(event) => void props.onSubmitReply(event)}>
								<label class={styles.fieldLabel}>
									<span>Reply</span>
									<textarea class={styles.textArea} rows={4} value={props.replyBody} placeholder="Write your reply..." onInput={(event) => props.onReplyBodyInput(event.currentTarget.value)} />
								</label>

								<Show when={props.messageActionError}>{(message) => <p class={`${styles.feedbackMessage} ${styles.feedbackError}`}>{message()}</p>}</Show>
								<Show when={props.messageActionSuccess}>{(message) => <p class={`${styles.feedbackMessage} ${styles.feedbackSuccess}`}>{message()}</p>}</Show>

								<div class={styles.replyActions}>
									<button class={styles.primaryAction} type="submit" disabled={props.sendingReply}>
										{props.sendingReply ? "Sending..." : "Send reply"}
									</button>
								</div>
							</form>
						</>
					)}
				</Show>
			</Show>
		</Show>
	</article>
);
