'use client';
import { useEffect, useRef, useState } from 'react';
import { api } from '@/lib/api';
import { useAuth } from '@/lib/auth-context';
import { formatDateTime, capitalizeFirst } from '@/lib/format';

export interface ChatComment {
  id: string | number;
  body: string;
  author_name?: string | null;
  author_id?: number | null;
  created_at?: string | null;
}

const REF_RE = /((?:DEV|ACT)-\d{4}-\d+(?:-S\d+)?|SMP-\d{4}-\d+)/g;

/** Turn deviation/sample reference numbers into search links. */
export function renderLinked(text: string): React.ReactNode[] {
  const parts = String(text ?? '').split(REF_RE);
  const isRef = /^((?:DEV|ACT)-\d{4}-\d+(?:-S\d+)?|SMP-\d{4}-\d+)$/;
  return parts.map((p, i) => {
    if (!isRef.test(p)) return <span key={i}>{p}</span>;
    const isSample = /^SMP-/.test(p);
    return (
      <a key={i} className="no-underline hover:underline font-mono text-xs" title={`Open ${p}`}
        href={isSample ? `/samples?search=${encodeURIComponent(p)}` : `/actions?search=${encodeURIComponent(p)}`}
        onClick={(e) => e.stopPropagation()}>
        {p}
      </a>
    );
  });
}

interface Suggestion { ref: string; title: string; kind: string }

/** Chat-style thread: own messages right, everyone else's left. */
export function CommentThread({ comments }: { comments: ChatComment[] }) {
  const { user } = useAuth();
  if (!comments.length) return <p className="text-sm text-slate-500">No comments yet — start the discussion.</p>;
  return (
    <div className="space-y-2" role="log" aria-label="Comments">
      {comments.map((c) => {
        const mine = user && c.author_id != null && Number(c.author_id) === Number(user.id);
        return (
          <div key={c.id} className={`flex ${mine ? 'justify-end' : 'justify-start'}`}>
            <div
              className={`max-w-[85%] rounded-2xl px-3 py-2 ${mine ? 'rounded-br-md' : 'rounded-bl-md'}`}
              style={mine
                ? { background: 'var(--ink)', color: 'var(--bg)' }
                : { background: 'var(--surface)', border: '1px solid var(--line)' }}>
              {!mine && <p className="text-[11px] font-bold" style={{ color: 'var(--muted)' }}>{c.author_name ?? 'User'}</p>}
              <p className="text-sm whitespace-pre-wrap break-words">{renderLinked(c.body)}</p>
              {!!c.created_at && (
                <p className="text-[10px] mt-0.5 text-right opacity-70">{formatDateTime(c.created_at)}</p>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/**
 * Comment composer with @-mention autocomplete for deviation/sample numbers.
 * Type @ to search (e.g. "@ACT-2026" or "@stability"), pick to insert the reference.
 */
export function CommentBox({ onSubmit, placeholder }: {
  onSubmit: (body: string) => Promise<void>; placeholder?: string;
}) {
  const [text, setText] = useState('');
  const [busy, setBusy] = useState(false);
  const [sugs, setSugs] = useState<Suggestion[]>([]);
  const [open, setOpen] = useState(false);
  const boxRef = useRef<HTMLDivElement>(null);
  const areaRef = useRef<HTMLTextAreaElement>(null);

  const atQuery = (() => {
    const m = /@([\w.-]*)$/.exec(text);
    return m ? m[1] : null;
  })();

  useEffect(() => {
    if (atQuery == null) { setOpen(false); setSugs([]); return; }
    let live = true;
    const t = setTimeout(async () => {
      try {
        const [a, s] = await Promise.all([
          api.get(`/api/v1/actions?search=${encodeURIComponent(atQuery)}&limit=5`).catch(() => null),
          api.get(`/api/v1/samples?search=${encodeURIComponent(atQuery)}&limit=5`).catch(() => null),
        ]);
        if (!live) return;
        const out: Suggestion[] = [
          ...((a?.data ?? []) as any[]).map((r: any) => ({ ref: r.reference_number, title: r.title, kind: 'deviation' })),
          ...((s?.data ?? []) as any[]).map((r: any) => ({ ref: r.sample_number, title: r.sample_name, kind: 'sample' })),
        ].slice(0, 8);
        setSugs(out); setOpen(true);
      } catch { /* ignore */ }
    }, 250);
    return () => { live = false; clearTimeout(t); };
  }, [atQuery]);

  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, [open ]);

  const pick = (ref: string) => {
    setText((t) => t.replace(/@[\w.-]*$/, `${ref} `));
    setOpen(false);
    areaRef.current?.focus();
  };

  const send = async () => {
    if (!text.trim() || busy) return;
    setBusy(true);
    try {
      await onSubmit(text.trim());
      setText('');
    } finally { setBusy(false); }
  };

  return (
    <div ref={boxRef} className="relative space-y-2">
      <textarea
        ref={areaRef}
        className="input"
        rows={2}
        aria-label={placeholder ?? 'Add a comment (use @ to reference deviations or samples)'}
        placeholder={placeholder ?? 'Add a comment… (type @ for refs)'}
        value={text}
        onChange={(e) => setText(capitalizeFirst(e.target.value))}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) send();
          if (e.key === 'Escape') setOpen(false);
        }}
      />
      {open && sugs.length > 0 && (
        <ul role="listbox" aria-label="Reference suggestions"
          className="absolute z-30 left-0 right-0 bottom-full mb-1 rounded-xl border shadow-lg overflow-hidden max-h-52 overflow-y-auto"
          style={{ background: 'var(--surface)', borderColor: 'var(--line)' }}>
          {sugs.map((s) => (
            <li key={`${s.kind}-${s.ref}`}>
              <button type="button" role="option" aria-selected="false"
                className="w-full text-left px-3 py-2 text-sm hover:bg-slate-500/10 flex gap-2 items-center"
                onClick={() => pick(s.ref)}>
                <span className="font-mono text-xs font-bold whitespace-nowrap">{s.ref}</span>
                <span className="truncate text-slate-500">{s.title}</span>
                <span className="badge bg-slate-100 ml-auto shrink-0">{s.kind}</span>
              </button>
            </li>
          ))}
        </ul>
      )}
      <div className="flex justify-end">
        <button className="btn-primary btn-sm" disabled={busy || !text.trim()} onClick={send}>
          {busy ? 'Posting…' : 'Post comment'}
        </button>
      </div>
    </div>
  );
}
