'use client';

import Link from 'next/link';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { zoneLabel } from '@/features/settings/ui/accountDefaultsZones';
import type { CalendarEvent } from '../../types';

/**
 * #487: a Google Calendar event that is not a CRM meeting opens its details here (time,
 * attendees, location, Join, Open in Google Calendar) instead of doing nothing on click.
 */

const RESPONSE: Record<string, string> = {
  accepted: 'Yes',
  declined: 'No',
  tentative: 'Maybe',
  needsAction: 'Awaiting',
};

function whenText(e: CalendarEvent, timeZone: string): string {
  if (e.allDay) {
    const fmt = new Intl.DateTimeFormat('en-US', {
      timeZone: 'UTC',
      weekday: 'long',
      month: 'long',
      day: 'numeric',
      year: 'numeric',
    });
    return `${fmt.format(new Date(`${e.startDate}T00:00:00Z`))} · All day`;
  }
  const start = new Date(e.startsAt);
  const day = new Intl.DateTimeFormat('en-US', {
    timeZone,
    weekday: 'long',
    month: 'long',
    day: 'numeric',
    year: 'numeric',
  }).format(start);
  const time = new Intl.DateTimeFormat('en-US', { timeZone, hour: 'numeric', minute: '2-digit' });
  return `${day} · ${time.format(start)} - ${time.format(new Date(e.endsAt))}`;
}

export function EventPopover({
  event,
  timeZone,
  onClose,
}: {
  event: CalendarEvent | null;
  timeZone: string;
  onClose: () => void;
}) {
  const e = event;
  return (
    <CrmModal id="calendarEventPopover" open={e !== null} onClose={onClose}>
      <ModalHeader id="calendarEventPopover" title={e?.title ?? '(No title)'} onClose={onClose} />
      <div className="modal__body">
        {e ? (
          <>
            <p className="evp-line">
              <CrmIcon name="clock" className="iconSize-16" />
              <span>
                {whenText(e, timeZone)}
                <span className="evp-muted"> ({zoneLabel(timeZone, new Date(e.startsAt))})</span>
              </span>
            </p>
            {e.location ? (
              <p className="evp-line">
                <CrmIcon name="map-pin" className="iconSize-16" />
                <span>{e.location}</span>
              </p>
            ) : null}
            {e.organizerEmail ? (
              <p className="evp-line">
                <CrmIcon name="user" className="iconSize-16" />
                <span>
                  Organizer <span className="evp-muted">{e.organizerEmail}</span>
                </span>
              </p>
            ) : null}
            {e.attendees.length ? (
              <div className="evp-line">
                <CrmIcon name="users" className="iconSize-16" />
                <div>
                  <p className="evp-head">
                    {e.attendees.length} attendee{e.attendees.length === 1 ? '' : 's'}
                  </p>
                  <ul className="evp-list">
                    {e.attendees.map((a) => {
                      // The CRM names the linked contacts, not their emails: match by name.
                      const contact = a.name
                        ? e.crmMeeting?.linked.find(
                            (l) =>
                              l.objectType === 'contact' &&
                              l.name.toLowerCase() === a.name?.toLowerCase(),
                          )
                        : undefined;
                      return (
                        <li key={a.email}>
                          {contact ? (
                            <Link className="link" href={`/contacts/${contact.id}`}>
                              {a.name}
                            </Link>
                          ) : (
                            <span>{a.name ?? a.email}</span>
                          )}
                          <span className="evp-muted">
                            {a.response ? (RESPONSE[a.response] ?? a.response) : ''}
                          </span>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              </div>
            ) : null}
          </>
        ) : null}
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Close
        </button>
        {e?.htmlLink ? (
          <a
            className="btn-crm btn-crm--outline"
            href={e.htmlLink}
            target="_blank"
            rel="noreferrer"
          >
            Open in Google Calendar
          </a>
        ) : null}
        {e?.meetingUrl ? (
          <a
            className="btn-crm btn-crm--primary"
            href={e.meetingUrl}
            target="_blank"
            rel="noreferrer"
          >
            Join
          </a>
        ) : null}
      </div>
    </CrmModal>
  );
}
