'use client';

import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { errorText } from '@/lib/api/errors';
import { listLinkedRecords } from '../api.client';
import type { LinkedRecord, ObjectRecord } from '../types';

const PAGE = 9;

const RECORD_PATHS: Record<string, string> = {
  contact: '/contacts',
  company: '/companies',
  deal: '/deals',
};

/**
 * The panel under an expanded row: the record's linked records of one type (picked in the
 * "Associated" menu, with counts), searchable, nine at a time.
 */
export function RowAssociations({
  objectKey,
  record,
  types,
}: {
  objectKey: string;
  record: ObjectRecord;
  /** Linked record types to offer, with their plural labels. */
  types: Array<{ type: string; plural: string }>;
}) {
  const counts = record.linkCounts ?? {};
  const first = types.find((t) => (counts[t.type] ?? 0) > 0) ?? types[0];
  const [type, setType] = useState(first?.type ?? 'contact');
  const [rows, setRows] = useState<LinkedRecord[]>([]);
  const [cursor, setCursor] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [query, setQuery] = useState('');
  const typeRef = useRef(type);
  typeRef.current = type;

  // QA #554: an object that lists no associated objects has no types to offer, so nothing to load.
  const none = types.length === 0;

  useEffect(() => {
    if (none) return;
    let alive = true;
    setLoading(true);
    setError(null);
    setRows([]);
    setCursor(null);
    listLinkedRecords({ fromType: objectKey, fromId: record.id, toType: type, limit: PAGE })
      .then((page) => {
        if (!alive) return;
        setRows(page.data);
        setCursor(page.nextCursor);
      })
      .catch((err: unknown) => {
        if (alive) setError(errorText(err));
      })
      .finally(() => {
        if (alive) setLoading(false);
      });
    return () => {
      alive = false;
    };
  }, [objectKey, record.id, type, none]);

  if (none) {
    return (
      <div className="evl-assoc">
        <p className="ev-help">No associated records of this type.</p>
      </div>
    );
  }

  const more = async () => {
    if (!cursor) return;
    const wanted = type;
    setLoading(true);
    try {
      const page = await listLinkedRecords({
        fromType: objectKey,
        fromId: record.id,
        toType: wanted,
        limit: 100,
        cursor,
      });
      // The type changed while this page loaded: its rows belong to the old list.
      if (typeRef.current !== wanted) return;
      setRows((cur) => [...cur, ...page.data]);
      setCursor(page.nextCursor);
    } catch (err) {
      if (typeRef.current === wanted) setError(errorText(err));
    } finally {
      if (typeRef.current === wanted) setLoading(false);
    }
  };

  const q = query.trim().toLowerCase();
  const shown = q ? rows.filter((r) => (r.name ?? '').toLowerCase().includes(q)) : rows;
  const count = counts[type];
  const base = RECORD_PATHS[type];

  return (
    <div className="evl-assoc">
      <div className="evl-assoc__bar">
        <span className="evl-assoc__label">Associated</span>
        <select
          className="input evl-assoc__type"
          aria-label="Associated record type"
          value={type}
          onChange={(e) => {
            setType(e.target.value);
            setQuery('');
          }}
        >
          {types.map((t) => (
            <option key={t.type} value={t.type}>
              {t.plural}
              {counts[t.type] !== undefined ? ` (${counts[t.type]})` : ''}
            </option>
          ))}
        </select>
        <div className="ev-search evl-assoc__search">
          <input
            type="search"
            className="input"
            placeholder="Search"
            aria-label="Search associated records"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </div>
      </div>
      {error ? <p className="ev-help ev-help--danger">{error}</p> : null}
      {!loading && rows.length === 0 && !error ? (
        <p className="ev-help">No associated records of this type.</p>
      ) : null}
      <ul className="evl-assoc__grid">
        {shown.map((r) => (
          <li key={r.associationId}>
            {base ? (
              <Link href={`${base}/${r.id}`} className="evl-assoc__name">
                {r.name || 'Untitled'}
              </Link>
            ) : (
              <span className="evl-assoc__name">{r.name || 'Untitled'}</span>
            )}
            {r.labels.length > 0 || r.isPrimary ? (
              <span className="evl-assoc__sub">
                {[r.isPrimary ? 'Primary' : null, ...r.labels.map((l) => l.name)]
                  .filter(Boolean)
                  .join(' · ')}
              </span>
            ) : null}
          </li>
        ))}
      </ul>
      {loading ? <p className="ev-help">Loading…</p> : null}
      {cursor && !loading ? (
        <button type="button" className="ev-link" onClick={() => void more()}>
          View all {typeof count === 'number' ? `${count} ` : ''}associated records
        </button>
      ) : null}
    </div>
  );
}
