'use client';

import Link from 'next/link';
import { Fragment, useState, type ReactNode } from 'react';
import {
  byDirection,
  duplicateCountText,
  generatedDate,
  generatedWithTime,
  lastTalkedLine,
  missingHeading,
  sentimentBasis,
  SECTIONS,
  shortDate,
  toggleSection,
  type CatchUpSection,
  type DuplicateCount,
  type Interaction,
  type Missing,
} from './catchup';

/**
 * B11: the company record page's Catch-up tab, the 28 Oct design's (`record-layout.js:125`,
 * `record-tabs.js:66-72`, `:115`, `:155-170`) on real data. Company only: Contacts' Intelligence
 * tab and Deals keep `SampleInsights` / `SampleCard` (`RecordTabs.tsx`). Every style is scoped
 * under `.company-catchup` (`company-details.css`). AI is out: no Company insights card (its body
 * is only the Ask box), no ✦ AI badges, no sentiment verdict.
 */

export type InteractionsState =
  { status: 'loading' } | { status: 'error' } | { status: 'ok'; list: Interaction[] };

export interface CompanyCatchUpProps {
  missing: Missing;
  interactions: InteractionsState;
  /** The record's first related contact, for the design's last-talked line. */
  contactName: string | null;
  /** When the interactions were loaded (the design's "Generated"). */
  generatedAt: Date;
  timeZone: string;
  duplicates: DuplicateCount;
  /** Settings > Properties, the design's Data agent link; null hides it (P1 `propertySettingsHref`). */
  dataAgentHref: string | null;
  onCreateEmail: () => void;
  /** Set when the person can't send email from here (read-only, deleted): the button is off. */
  emailDisabledTitle?: string;
  /** Sections that start closed (tests); the design starts with every one open. */
  initialClosed?: CatchUpSection[];
  /** The company is deleted (an admin's view): nothing loads for it. */
  deleted?: boolean;
}

/** The cards under each section heading, for its button's `aria-controls`. */
const SECTION_CARDS: Record<CatchUpSection, string[]> = {
  Overview: ['interactions'],
  Health: ['sentiment', 'challenges', 'feedback'],
  'Data quality': ['missing', 'duplicates'],
};
const cardDomId = (card: string) => `catchup-${card}`;

const Chevron = () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2.2"
    strokeLinecap="round"
    strokeLinejoin="round"
    aria-hidden="true"
  >
    <path d="m6 9 6 6 6-6" />
  </svg>
);

/** The design's `card()` (`record-tabs.js:66-72`), with no header icons left. */
function Card({
  id,
  title,
  hidden,
  children,
}: {
  id: string;
  title: string;
  hidden?: boolean;
  children: ReactNode;
}) {
  return (
    <section className="rt-card" id={cardDomId(id)} data-rt-card={id} hidden={hidden}>
      <header className="rt-card__head">
        <h3>{title}</h3>
        <span className="rt-card__acts" />
      </header>
      <div className="rt-card__body">{children}</div>
    </section>
  );
}

function List({ items, timeZone }: { items: Interaction[]; timeZone: string }) {
  if (!items.length) return <p className="rt-muted">No interactions.</p>;
  return (
    <ul className="rt-ilist">
      {items.map((i) => (
        <li key={i.id}>
          <strong>{i.title}</strong>
          <span>{shortDate(i.at, timeZone)}</span>
        </li>
      ))}
    </ul>
  );
}

/** R10b: Catch-up's cards (the user's answer 1b), which a company tab can hold since R10b. */
export const CATCHUP_CARDS = [
  'interactions',
  'sentiment',
  'challenges',
  'feedback',
  'missing',
  'duplicates',
];

/**
 * R10b: one Catch-up card by id (record-tabs.js:155-170), drawn by the company page from a tab's
 * items inside `.company-catchup` (their scoped styles); `null` for an unknown id.
 */
export function CatchUpCard({
  id,
  hidden,
  ...props
}: { id: string; hidden?: boolean } & CompanyCatchUpProps) {
  const { missing, interactions, timeZone, generatedAt, duplicates } = props;
  const list = interactions.status === 'ok' ? interactions.list : [];
  const split = byDirection(list);
  const failed = interactions.status === 'error';
  const loading = interactions.status === 'loading';
  switch (id) {
    case 'interactions':
      return (
        <Card id="interactions" title="Recent interactions" hidden={hidden}>
          {loading ? <p className="rt-muted">Loading interactions…</p> : null}
          {failed ? <p className="rt-muted">Couldn&apos;t load interactions.</p> : null}
          {interactions.status === 'ok' ? (
            <>
              <p className="rt-muted">{generatedWithTime(generatedAt, timeZone)}</p>
              <p>{lastTalkedLine(list, props.contactName, timeZone)}</p>
            </>
          ) : null}
          <button
            type="button"
            className="rt-btn rt-btn--sm"
            disabled={Boolean(props.emailDisabledTitle)}
            title={props.emailDisabledTitle}
            onClick={props.onCreateEmail}
          >
            ✉ Create an email
          </button>
          {interactions.status === 'ok' ? (
            <div className="rt-iox">
              <h4>Inbound</h4>
              <List items={split.inbound} timeZone={timeZone} />
              <h4>Outbound</h4>
              <List items={split.outbound} timeZone={timeZone} />
            </div>
          ) : null}
        </Card>
      );
    case 'sentiment':
      return (
        <Card id="sentiment" title="Sentiment" hidden={hidden}>
          {interactions.status === 'ok' ? (
            <>
              <p className="rt-sent">
                <span className="rt-sent__dot rt-sent__dot--none" aria-hidden="true" />
                Not rated
              </p>
              <p className="rt-muted">{sentimentBasis(list.length)}</p>
            </>
          ) : (
            <p className="rt-muted">
              {failed ? "Couldn't load interactions." : 'Loading interactions…'}
            </p>
          )}
        </Card>
      );
    case 'challenges':
      return (
        <Card id="challenges" title="Challenges" hidden={hidden}>
          <p className="rt-muted">{generatedDate(generatedAt, timeZone)}</p>
          <p className="rt-muted">No challenges found.</p>
        </Card>
      );
    case 'feedback':
      return (
        <Card id="feedback" title="Positive feedback" hidden={hidden}>
          <p className="rt-muted">{generatedDate(generatedAt, timeZone)}</p>
          <p className="rt-muted">No customer feedback found.</p>
        </Card>
      );
    case 'missing':
      return (
        <Card id="missing" title="Missing data" hidden={hidden}>
          {missing.pending && !missing.failed ? (
            // Still loading: no partial list and never "has data" yet.
            <p className="rt-muted">Checking monitored properties…</p>
          ) : missing.labels.length ? (
            <>
              <p>{missingHeading(missing.labels.length)}</p>
              <ul className="rt-ul">
                {missing.labels.map((l) => (
                  <li key={l}>{l}</li>
                ))}
              </ul>
            </>
          ) : missing.failed ? null : (
            <div className="rt-empty">
              <span className="rt-check" aria-hidden="true">
                ✓
              </span>
              <span>All monitored properties have data.</span>
            </div>
          )}
          {missing.failed ? (
            <p className="rt-muted">
              Some properties couldn&apos;t be checked. Refresh the page to try again.
            </p>
          ) : null}
          <div className="rt-agent">
            <p>
              Missing data somewhere else? Use Data Agent to answer questions, create smart
              properties, transform your data, and enhance your workflows.
            </p>
            {props.dataAgentHref ? (
              <Link className="rt-pill rt-pill--ai" href={props.dataAgentHref}>
                ✦ Data agent
              </Link>
            ) : null}
          </div>
        </Card>
      );
    case 'duplicates':
      return (
        <Card id="duplicates" title="Duplicate records" hidden={hidden}>
          <p className={duplicates.status === 'ok' ? undefined : 'rt-muted'}>
            {duplicateCountText(duplicates)}
          </p>
          <p>There are no custom rules set up.</p>
          <p>
            <Link className="rt-link" href="/data-quality/duplicates?object=companies">
              Go to Manage Duplicates
            </Link>{' '}
            to set up a rule.
          </p>
        </Card>
      );
    default:
      return null;
  }
}

export function CompanyCatchUp(props: CompanyCatchUpProps) {
  const [closed, setClosed] = useState<Set<CatchUpSection>>(
    () => new Set(props.initialClosed ?? []),
  );
  const shut = (s: CatchUpSection) => closed.has(s);
  const heading = (s: CatchUpSection) => (
    <h2 className="rt-section">
      <button
        type="button"
        aria-expanded={!shut(s)}
        aria-controls={SECTION_CARDS[s].map(cardDomId).join(' ')}
        data-rt-sec=""
        onClick={() => setClosed((c) => toggleSection(c, s))}
      >
        <Chevron />
        {s}
      </button>
    </h2>
  );

  if (props.deleted) {
    return (
      <div className="company-catchup rt-panel" data-catchup>
        <p className="rt-muted">Catch-up isn&apos;t available for a deleted company.</p>
      </div>
    );
  }

  return (
    <div className="company-catchup rt-panel" data-catchup>
      {SECTIONS.map((s) => (
        <Fragment key={s}>
          {heading(s)}
          {SECTION_CARDS[s].map((id) => (
            <CatchUpCard key={id} id={id} hidden={shut(s)} {...props} />
          ))}
        </Fragment>
      ))}
    </div>
  );
}
