"use client";

import { useEffect, useMemo, useState } from "react";
import type { Message } from "@slackwsh/contracts";
import { dmTitle, isDmChannel, type ConversationRow } from "../lib/conversations";
import { IconCheck, IconLock, IconMessages, IconSearch, IconX } from "./icons";

interface ForwardMessageModalProps {
  message: Message;
  authorName: string;
  sourceLabel: string;
  conversations: ConversationRow[];
  busy: boolean;
  error: string | null;
  onClose: () => void;
  onSubmit: (destinationIds: string[], note: string) => void;
}

function conversationLabel(row: ConversationRow): string {
  return isDmChannel(row.channel.type) ? dmTitle(row) : `#${row.channel.name ?? "channel"}`;
}

export function ForwardMessageModal({
  message,
  authorName,
  sourceLabel,
  conversations,
  busy,
  error,
  onClose,
  onSubmit,
}: ForwardMessageModalProps) {
  const [query, setQuery] = useState("");
  const [note, setNote] = useState("");
  const [selected, setSelected] = useState<Set<string>>(() => new Set());

  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape" && !busy) onClose();
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [busy, onClose]);

  const visible = useMemo(() => {
    const needle = query.trim().toLowerCase();
    return conversations
      .filter((row) => !row.member?.isClosed)
      .filter((row) => !needle || conversationLabel(row).toLowerCase().includes(needle));
  }, [conversations, query]);

  function toggle(channelId: string) {
    setSelected((current) => {
      const next = new Set(current);
      if (next.has(channelId)) next.delete(channelId);
      else if (next.size < 10) next.add(channelId);
      return next;
    });
  }

  return (
    <div className="channel-invite-backdrop" role="presentation" onClick={() => { if (!busy) onClose(); }}>
      <form
        className="channel-invite-modal forward-message-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="forward-message-title"
        onClick={(event) => event.stopPropagation()}
        onSubmit={(event) => {
          event.preventDefault();
          if (selected.size > 0 && !busy) onSubmit([...selected], note);
        }}
      >
        <div className="channel-invite-head">
          <div>
            <h2 id="forward-message-title">Forward message</h2>
            <p>Share with up to 10 conversations.</p>
          </div>
          <button className="thread-close" type="button" onClick={onClose} aria-label="Close" disabled={busy}><IconX /></button>
        </div>

        <div className="forward-message-body">
          <label className="slack-member-search forward-search">
            <IconSearch />
            <input autoFocus value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search channels and people" aria-label="Search destinations" />
          </label>

          <div className="forward-destinations" role="listbox" aria-label="Forward destinations" aria-multiselectable="true">
            {visible.map((row) => {
              const id = String(row.channel.id);
              const checked = selected.has(id);
              const isDm = isDmChannel(row.channel.type);
              return (
                <button
                  type="button"
                  role="option"
                  aria-selected={checked}
                  className={checked ? "forward-destination selected" : "forward-destination"}
                  key={id}
                  onClick={() => toggle(id)}
                >
                  <span className="forward-destination-icon" aria-hidden="true">
                    {row.channel.type === "private" ? <IconLock /> : <IconMessages />}
                  </span>
                  <span><strong>{conversationLabel(row)}</strong><small>{isDm ? (row.channel.type === "group_dm" ? "Group message" : "Direct message") : row.channel.type === "private" ? "Private channel" : "Channel"}</small></span>
                  <i className="forward-checkbox" aria-hidden="true">{checked && <IconCheck />}</i>
                </button>
              );
            })}
            {visible.length === 0 && <div className="slack-member-empty"><strong>No conversations found</strong><span>Try another channel or person.</span></div>}
          </div>

          <label className="forward-note">
            <span>Add a message <small>(optional)</small></span>
            <textarea value={note} onChange={(event) => setNote(event.target.value)} maxLength={2_000} rows={3} placeholder="Add context for this message" />
          </label>

          <blockquote className="forward-preview">
            <span><strong>{authorName}</strong> in {sourceLabel}</span>
            <p>{message.text || "Message with attachments"}</p>
          </blockquote>
          {error && <p className="message-delete-error" role="alert">{error}</p>}
        </div>

        <div className="channel-invite-foot">
          <span className="forward-selection-count">{selected.size > 0 ? `${selected.size} selected` : "Choose a destination"}</span>
          <button type="button" className="screen-btn" onClick={onClose} disabled={busy}>Cancel</button>
          <button type="submit" className="screen-btn primary" disabled={busy || selected.size === 0}>{busy ? "Forwarding..." : "Forward"}</button>
        </div>
      </form>
    </div>
  );
}
