'use client';

import { useEffect, useRef, useState } from 'react';
import { useSelectedStoreId } from '@/lib/stores/store-context';
import {
  useMessages,
  usePostMessage,
  useDeleteMessage,
} from '@/lib/queries/use-messages';
import { MessageRow } from './message-row';
import { MessageComposer } from './message-composer';
import { AttachmentUploader } from './attachment-uploader';

interface Props {
  orderId: string;
  counterpartyName?: string;
  viewerRole: 'buyer' | 'seller' | 'admin';
  viewerUserId: string;
  readOnly?: boolean;
  /** When provided, every row renders a checkbox; the parent owns the
   *  selected-id set and reacts to onToggle. */
  selection?: { selectedIds: Set<string>; onToggle: (id: string) => void };
}

export function MessageThread({
  orderId,
  counterpartyName,
  viewerRole,
  viewerUserId,
  readOnly,
  selection,
}: Props) {
  const selectedStoreId = useSelectedStoreId();
  const storeId = viewerRole === 'seller' ? selectedStoreId : undefined;
  const list = useMessages(orderId, { storeId });
  const post = usePostMessage(orderId, storeId);
  const remove = useDeleteMessage(orderId, storeId);
  const scrollRef = useRef<HTMLDivElement | null>(null);
  const [pendingAttachmentIds, setPendingAttachmentIds] = useState<string[]>([]);
  const [composerKey, setComposerKey] = useState(0);

  const messages = list.data?.data ?? [];

  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages.length]);

  if (list.isError) {
    return (
      <p className="rounded bg-red-50 p-3 text-sm text-red-700">
        Couldn&apos;t load this conversation. Try refreshing.
      </p>
    );
  }

  const onSend = (body: string) => {
    post.mutate(
      {
        body,
        attachment_ids: pendingAttachmentIds.length ? pendingAttachmentIds : undefined,
      },
      {
        onSuccess: () => {
          setPendingAttachmentIds([]);
          setComposerKey((k) => k + 1);
        },
      },
    );
  };

  return (
    <div className="flex flex-col">
      <div
        ref={scrollRef}
        className="max-h-96 overflow-y-auto rounded-md border border-slate-200 bg-white p-3"
      >
        {list.isLoading && <p className="text-sm text-slate-400">Loading…</p>}
        {!list.isLoading && messages.length === 0 && (
          <p className="py-6 text-center text-sm text-slate-400">
            No messages yet. Start the conversation below.
          </p>
        )}
        {messages.map((m) => (
          <MessageRow
            key={m.id}
            message={m}
            viewerRole={viewerRole}
            viewerUserId={viewerUserId}
            counterpartyName={counterpartyName}
            onDelete={(id) => remove.mutate(id)}
            selectable={
              selection
                ? {
                    selected: selection.selectedIds.has(m.id),
                    onToggle: () => selection.onToggle(m.id),
                  }
                : undefined
            }
          />
        ))}
      </div>

      {!readOnly && (
        <>
          <AttachmentUploader
            key={`uploader-${composerKey}`}
            orderId={orderId}
            storeId={storeId}
            onChange={setPendingAttachmentIds}
            disabled={post.isPending}
          />

          <MessageComposer
            onSend={onSend}
            isPending={post.isPending}
            placeholder={`Message ${counterpartyName ?? 'the other party'}…`}
          />
        </>
      )}
    </div>
  );
}
