'use client';

import { useEffect, useRef, useState, type ReactNode } from 'react';
import { formatUserDate, readable, type ReadableContext } from '@/features/activities/readable';
import { RelatedRecordsCard } from '@/features/associations/ui/RelatedRecordsCard';
import { getContactTimeline } from '@/features/contacts/api.client';
import type { Contact, TimelineItem } from '@/features/contacts/types';
import { ContactAssociations } from '@/features/contacts/ui/ContactAssociations';
import { CollapsibleCard } from '@/features/contacts/ui/CollapsibleCard';
import { WebsiteActivityCard } from '@/features/contacts/ui/record/ContactSidebarCards';
import { AttachmentsSidebarCard } from '@/features/files/ui/AttachmentsCard';
import { listRecordLists, type RecordList } from '@/features/lists/api.client';
import { LinkedObjectCards } from '@/features/objects/ui/LinkedObjectCards';
import { ContactSubscriptionsCard } from '@/features/subscriptions/ui/ContactSubscriptionsCard';
import { errorText } from '@/lib/api/errors';

/**
 * Tasks and meetings looked through for the upcoming ones: the timeline goes by creation date for
 * tasks, so on a record with more than this an old open task can be missed.
 */
const UPCOMING_SCAN = 100;
const SHOWN = 5;

const whenOf = (item: TimelineItem): string =>
  String((item.type === 'task' ? (item.dueAt ?? item.dueDate) : item.startsAt) ?? '');

/** When an item stops being upcoming: a date-only task lasts until its day ends. */
const endOf = (when: string): number =>
  new Date(/^\d{4}-\d{2}-\d{2}$/.test(when) ? `${when}T23:59:59` : when).getTime();

/** Open tasks and scheduled meetings still to come, soonest first. */
export function upcomingActivities(items: TimelineItem[], now: number): TimelineItem[] {
  return items
    .filter((i) => {
      if (i.type === 'task' && i.status === 'completed') return false;
      if (i.type === 'meeting' && i.status === 'cancelled') return false;
      return (i.type === 'task' || i.type === 'meeting') && endOf(whenOf(i)) > now;
    })
    .sort((a, b) => endOf(whenOf(a)) - endOf(whenOf(b)));
}

/** The two timeline reads behind Recent and Upcoming activities (Contacts and, since B4, Companies). */
export function previewTimelineQueries(now: string) {
  return {
    // A meeting's date is when it happens: up to now, so future ones stay in Upcoming.
    recent: {
      limit: SHOWN,
      types: 'note,call,task,meeting,email,communication,postal_mail',
      to: now,
    },
    upcoming: { limit: UPCOMING_SCAN, types: 'task,meeting' },
  };
}

/** A record's timeline page, as `getContactTimeline` (or `getCompanyTimeline`) reads it. */
export type PreviewTimelineLoad = (
  id: string,
  params: { limit: number; types: string; to?: string },
) => Promise<{ data: TimelineItem[] }>;

/**
 * Mounts a card when it comes near the view: each one reads the API, and most are never seen.
 * `eager` mounts it at once (tests, which have no IntersectionObserver).
 */
export function WhenSeen({ children, eager = false }: { children: ReactNode; eager?: boolean }) {
  const ref = useRef<HTMLDivElement>(null);
  const [seen, setSeen] = useState(eager);
  useEffect(() => {
    const el = ref.current;
    if (!el || seen) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) setSeen(true);
      },
      { root: el.closest('.lp-side__body'), rootMargin: '120px' },
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [seen]);
  return (
    <div ref={ref} className="lp-pv__card">
      {seen ? children : null}
    </div>
  );
}

export function ActivityList({
  items,
  error,
  ctx,
  when,
  empty,
}: {
  items: TimelineItem[] | null;
  error: string | null;
  ctx: ReadableContext;
  when: (item: TimelineItem) => string;
  empty: string;
}) {
  if (error) return <p className="rp-empty">{error}</p>;
  if (items === null) return <p className="rp-empty">Loading…</p>;
  if (items.length === 0) return <p className="rp-empty">{empty}</p>;
  return (
    <ul className="rp-ov__acts">
      {items.map((item) => {
        const r = readable(item, ctx);
        return (
          <li key={item.id}>
            <strong>
              {r.title}
              {r.sentence ? (
                <span className="crm-d-block crm-fw-normal crm-fs-8 crm-text-muted">
                  {r.sentence}
                </span>
              ) : null}
            </strong>
            <span>
              {formatUserDate(when(item), {
                region: ctx.region,
                timeZone: ctx.timeZone,
                time: true,
              })}
            </span>
          </li>
        );
      })}
    </ul>
  );
}

/** Recent and Upcoming activities of a record: a contact's, or what `load` reads (B4, companies). */
export function ActivityCards({
  contactId,
  ctx,
  refreshKey,
  load = getContactTimeline,
}: {
  /** The record whose timeline this is (a contact unless `load` says otherwise). */
  contactId: string;
  ctx: ReadableContext;
  refreshKey: number;
  load?: PreviewTimelineLoad;
}) {
  const [recent, setRecent] = useState<TimelineItem[] | null>(null);
  const [upcoming, setUpcoming] = useState<TimelineItem[] | null>(null);
  const [recentError, setRecentError] = useState<string | null>(null);
  const [upcomingError, setUpcomingError] = useState<string | null>(null);
  useEffect(() => {
    let alive = true;
    setRecentError(null);
    setUpcomingError(null);
    const q = previewTimelineQueries(new Date().toISOString());
    load(contactId, q.recent).then(
      (page) => {
        if (alive) setRecent(page.data);
      },
      (err: unknown) => {
        if (alive) setRecentError(errorText(err));
      },
    );
    load(contactId, q.upcoming).then(
      (page) => {
        if (alive) setUpcoming(upcomingActivities(page.data, Date.now()).slice(0, SHOWN));
      },
      (err: unknown) => {
        if (alive) setUpcomingError(errorText(err));
      },
    );
    return () => {
      alive = false;
    };
  }, [contactId, refreshKey, load]);
  return (
    <>
      <CollapsibleCard title="Recent activities" cardId="pv-recent">
        <ActivityList
          items={recent}
          error={recentError}
          ctx={ctx}
          when={(item) => item.occurredAt}
          empty="No activity yet."
        />
      </CollapsibleCard>
      <CollapsibleCard title="Upcoming activities" cardId="pv-upcoming">
        <ActivityList
          items={upcoming}
          error={upcomingError}
          ctx={ctx}
          when={whenOf}
          empty="No upcoming activities."
        />
      </CollapsibleCard>
    </>
  );
}

/** The record's static and active lists, as `/lists/memberships` gives them. */
function SegmentsCard({
  contactId,
  region,
  timeZone,
}: {
  contactId: string;
  region: ReadableContext['region'];
  timeZone: string;
}) {
  const [lists, setLists] = useState<RecordList[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  useEffect(() => {
    let alive = true;
    listRecordLists('contact', contactId).then(
      (rows) => {
        if (alive) setLists(rows);
      },
      (err: unknown) => {
        if (alive) setError(errorText(err));
      },
    );
    return () => {
      alive = false;
    };
  }, [contactId]);
  return (
    <CollapsibleCard title="Segment memberships" cardId="pv-segments">
      {error ? (
        <p className="rp-empty">{error}</p>
      ) : lists === null ? (
        <p className="rp-empty">Loading…</p>
      ) : lists.length === 0 ? (
        <p className="rp-empty">Not in any segment.</p>
      ) : (
        <ul className="rp-ov__acts">
          {lists.map((list) => (
            <li key={list.listId}>
              <strong>{list.name}</strong>
              <span>{formatUserDate(list.addedAt, { region, timeZone })}</span>
            </li>
          ))}
        </ul>
      )}
    </CollapsibleCard>
  );
}

/**
 * The preview's cards after the design's About and Associations: the record page's own, each
 * loaded when it comes into view. The drawers they open stack over the panel (list-audit.css).
 */
export function ContactPreviewCards({
  contact,
  name,
  canEdit,
  ctx,
  refreshKey,
  onChanged,
}: {
  contact: Contact;
  name: string;
  canEdit: boolean;
  ctx: ReadableContext;
  refreshKey: number;
  onChanged: () => Promise<void>;
}) {
  return (
    <>
      <WhenSeen>
        <ActivityCards contactId={contact.id} ctx={ctx} refreshKey={refreshKey} />
      </WhenSeen>
      <WhenSeen>
        <RelatedRecordsCard
          type="contact"
          recordId={contact.id}
          recordName={name}
          canEdit={canEdit}
        />
      </WhenSeen>
      <WhenSeen>
        <ContactAssociations
          contact={contact}
          contactName={name}
          canEdit={canEdit}
          onChanged={onChanged}
        />
      </WhenSeen>
      <WhenSeen>
        <LinkedObjectCards
          anchorType="contact"
          variant="contact"
          anchorId={contact.id}
          anchorName={name}
          canEdit={canEdit}
        />
      </WhenSeen>
      <WhenSeen>
        <ContactSubscriptionsCard contactId={contact.id} canEdit={canEdit} />
      </WhenSeen>
      <WhenSeen>
        <AttachmentsSidebarCard
          link={{ type: 'contact', id: contact.id }}
          canEdit={canEdit}
          refreshKey={refreshKey}
        />
      </WhenSeen>
      <WhenSeen>
        <SegmentsCard contactId={contact.id} region={ctx.region} timeZone={ctx.timeZone} />
      </WhenSeen>
      <WhenSeen>
        <WebsiteActivityCard contactId={contact.id} region={ctx.region} timeZone={ctx.timeZone} />
      </WhenSeen>
    </>
  );
}
