import { For, Show, type JSX } from "solid-js";

import { SourceAttribution } from "~/components/SourceAttribution";
import { AnswerBlock } from "~/components/AnswerBlock";
import { formatWhen } from "~/lib/format";

import styles from "~/routes/[handle].module.css";

interface AnswerLike {
  id: string;
  content: string;
  createdAt: Date | string;
  sourceType?: string | null;
  sourceUri?: string | null;
  sourceData?: string | null;
}

interface AuthorLike {
  handle: string;
  displayName?: string | null;
}

interface QuestionCardProps {
  id?: string;
  content: string;
  createdAt: Date | string;
  anonymous: boolean;
  author?: AuthorLike | null;
  sourceType?: string | null;
  sourceUri?: string | null;
  sourceData?: string | null;
  answers?: AnswerLike[];
  /** When true, show a "Pending answer" hint if no answers are present. */
  showPendingHint?: boolean;
  /** Optional slot for trailing content (e.g. "Click to answer →"). */
  trailing?: JSX.Element;
}

export function QuestionCard(props: QuestionCardProps) {
  const authorLabel = () => {
    if (props.anonymous) return "Anonymous";
    return props.author?.displayName || props.author?.handle || "Unknown";
  };

  return (
    <article id={props.id} class={styles.questionCard}>
      <div class={styles.questionContent}>{props.content}</div>
      <div class={styles.questionMeta}>
        {authorLabel()} · {formatWhen(props.createdAt)}
        <SourceAttribution
          sourceType={props.sourceType || "askimut"}
          sourceUri={props.sourceUri}
          sourceData={props.sourceData}
        />
      </div>
      <Show when={props.answers}>
        <For each={props.answers}>
          {(a) => (
            <AnswerBlock
              content={a.content}
              createdAt={a.createdAt}
              sourceType={a.sourceType}
              sourceUri={a.sourceUri}
              sourceData={a.sourceData}
            />
          )}
        </For>
      </Show>
      <Show
        when={
          props.showPendingHint && (props.answers?.length ?? 0) === 0
        }
      >
        <div class={styles.pendingIndicator}>
          <span class={styles.pendingText}>Pending answer</span>
        </div>
      </Show>
      {props.trailing}
    </article>
  );
}

export default QuestionCard;
