'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { getObjectRecord } from '@/features/objects/api.client';
import type { ObjectRecord } from '@/features/objects/types';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { eventFields } from '../preview';
import { NO_VALUE } from '../segment';
import { SegDrawer } from './primitives';

/**
 * `#vcsEventSideDrawer` (PHP:3422-3534, JS:3549-3621), opened from the contact drawer's Events
 * cards (SEG2a C5). Reads the event (`GET /objects/event/records/:id`); its actions stay coming
 * soon. A failed read leaves the name and `--`, with the error toast.
 */
export function EventPreviewDrawer({
  open,
  onClose,
  eventName,
  eventId = null,
}: {
  open: boolean;
  onClose: () => void;
  eventName: string;
  eventId?: string | null;
}) {
  const toast = useToast();
  const [record, setRecord] = useState<ObjectRecord | null>(null);
  useEffect(() => {
    if (!open || !eventId) return;
    let live = true;
    setRecord(null);
    getObjectRecord('event', eventId).then(
      (r) => {
        if (live) setRecord(r);
      },
      (err: unknown) => {
        if (live) toast(errorText(err), 'danger');
      },
    );
    return () => {
      live = false;
    };
    // Read again only for another event; toast may change identity every render.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, eventId]);
  return (
    <EventPreviewView
      open={open}
      onClose={onClose}
      eventName={eventName}
      eventId={eventId}
      record={record && record.id === eventId ? record : null}
    />
  );
}

/** The drawer with its record (`null` while loading or after a failed read). For tests too. */
export function EventPreviewView({
  open,
  onClose,
  eventName,
  eventId = null,
  record,
}: {
  open: boolean;
  onClose: () => void;
  eventName: string;
  eventId?: string | null;
  record: ObjectRecord | null;
}) {
  const { timeZone, regionFormat } = useUserPrefs();
  const [aboutOpen, setAboutOpen] = useState(true);
  const fields = eventFields(record, eventName, timeZone, regionFormat);
  const name = fields[0]![1] || NO_VALUE;

  return (
    <SegDrawer
      open={open}
      onClose={onClose}
      label="Event preview"
      id="vcsEventSideDrawer"
      className="lp-side--preview"
    >
      <header className="lp-side__head vcs-drawer-head">
        <h2 className="lp-side__title crm-fs-5 crm-fw-700 crm-mb-0" id="vcsEventDrawerTitle">
          {name}
        </h2>
        <div className="lp-side__tools">
          <button
            type="button"
            className="lp-icon-btn"
            id="vcsEventDrawerClose"
            aria-label="Close event preview"
            onClick={onClose}
          >
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </div>
      </header>

      <div className="vcs-drawer-subbar">
        <Link
          className="vcs-drawer-rec-link"
          href={eventId ? `/events/${eventId}` : '/events'}
          id="vcsEventRecordLink"
        >
          View record
        </Link>
      </div>

      <div className="lp-side__body">
        <section className="lp-pv__sec">
          <div className="lp-pv__sh-row">
            <h3>
              <button
                type="button"
                className="lp-pv__sh"
                aria-expanded={aboutOpen}
                onClick={() => setAboutOpen((v) => !v)}
              >
                <CrmIcon name="chevron-down" className="lp-i iconSize-14" />
                <span>About this Event</span>
              </button>
            </h3>
          </div>
          <div className="lp-pv__fields">
            {fields.map(([label, value, id]) => (
              <div className="lp-pv__field" key={label}>
                <span className="lp-pv__label">{label}</span>
                <div className="lp-pv__field-row">
                  <div className="lp-pv__val" id={id}>
                    {value}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </section>
      </div>
    </SegDrawer>
  );
}
