'use client';

/**
 * The conversation's contact panel as the design draws it (inbox-hs.js renderSide): the contact
 * card, "About this contact", then one collapsible section per kind of linked record with its
 * cards (Companies, Tickets, Deals: the ones the CRM has data for) and the "Ticket" section with
 * Create ticket. A ticket created from this conversation is tagged "This conversation".
 * "Conversations" (HUB-366) are the contact's other conversations in the user's own mailbox.
 */
import Link from 'next/link';
import { useState, type ReactNode } from 'react';
import type { ContactEmailThread } from '@/features/contacts/types';
import { objectRecordPath } from '@/features/objects/paths';
import { displayName, formatAmount, messageTime, shownAddress } from '../format';
import type { ContactDetail, EmailParticipant, InboxTicketCard } from '../types';
import { IxIcon, ixInitials } from './ix';

type SectionKey = 'about' | 'companies' | 'tickets' | 'deals' | 'past';

const shortDate = (value: string | null | undefined) => {
  if (!value) return '--';
  // Date-only values (close dates) are calendar days: no time zone shift.
  const [y, m, d] = value.slice(0, 10).split('-').map(Number);
  if (!y || !m || !d) return value;
  return new Date(y, m - 1, d).toLocaleDateString(undefined, {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  });
};

function Section({
  id,
  title,
  open,
  onToggle,
  children,
}: {
  id: SectionKey;
  title: string;
  open: boolean;
  onToggle: (id: SectionKey) => void;
  children: ReactNode;
}) {
  return (
    <section className="ix-sec">
      <header>
        <button
          type="button"
          className="ix-sec__t"
          aria-expanded={open}
          onClick={() => onToggle(id)}
        >
          <IxIcon name="chev" className={open ? undefined : 'is-rot'} />
          {title}
        </button>
      </header>
      {open ? children : null}
    </section>
  );
}

function Empty({ text }: { text: string }) {
  return (
    <div className="ix-sec__e ix-sec__e--l">
      <p>{text}</p>
    </div>
  );
}

export function InboxSidebar({
  party,
  caution,
  pastScope = 'your mailbox',
  contact,
  contactLoading,
  lifecycleLabel,
  leadStatusLabel,
  nextTask,
  tickets,
  canCreateTicket,
  createTicketTitle,
  onCreateTicket,
  past,
  pastHasMore,
  onOpenConversation,
}: {
  party: EmailParticipant;
  /** A warning about who this is, such as an address a chat visitor only typed. */
  caution?: string;
  /** Where the other conversations come from, for the empty text. */
  pastScope?: string;
  contact: ContactDetail | null;
  contactLoading: boolean;
  lifecycleLabel: string;
  leadStatusLabel: string;
  nextTask: string | null;
  tickets: InboxTicketCard[];
  canCreateTicket: boolean;
  createTicketTitle?: string;
  onCreateTicket: () => void;
  /** The contact's other conversations; null while loading or when they could not be loaded. */
  past: ContactEmailThread[] | null;
  pastHasMore: boolean;
  onOpenConversation: (id: string) => void;
}) {
  const [closed, setClosed] = useState<Partial<Record<SectionKey, boolean>>>({});
  const toggle = (k: SectionKey) => setClosed((c) => ({ ...c, [k]: !c[k] }));
  const isOpen = (k: SectionKey) => !closed[k];

  const name = contact
    ? [contact.firstName, contact.lastName].filter(Boolean).join(' ') || contact.email || 'Contact'
    : displayName(party);
  const contactHref = contact ? `/contacts/${contact.id}` : null;

  return (
    <>
      <div className="ix-card">
        <span className="ix-av ix-av--lg">{ixInitials(name)}</span>
        <div>
          <p className="ix-card__n">
            {contactHref ? (
              <>
                <Link href={contactHref} title={name}>
                  {name}
                </Link>
                <Link
                  className="ix-icon"
                  href={contactHref}
                  aria-label="Open contact record"
                  title="Open contact record"
                >
                  <IxIcon name="ext" className="ix-i--sm" />
                </Link>
              </>
            ) : (
              name
            )}
          </p>
          <p className="ix-card__c">
            {contact
              ? contact.companies[0]?.name || contact.email || ''
              : shownAddress(party.email)}
          </p>
        </div>
      </div>
      {caution ? (
        <p className="ix-caution" role="note">
          {caution}
        </p>
      ) : null}

      {contactLoading ? (
        <p className="ix-sec__e ix-sec__e--l ix-muted">Looking up contact…</p>
      ) : !contact ? (
        <Empty
          text={
            shownAddress(party.email)
              ? 'This address is not a contact in the CRM.'
              : 'No email address was given, so no CRM contact is shown.'
          }
        />
      ) : (
        <>
          <Section id="about" title="About this contact" open={isOpen('about')} onToggle={toggle}>
            <dl className="ix-props">
              <div>
                <dt>Email</dt>
                <dd>{contact.email || '--'}</dd>
              </div>
              <div>
                <dt>Phone Number</dt>
                <dd>{contact.phone || '--'}</dd>
              </div>
              <div>
                <dt>Contact owner</dt>
                <dd>{contact.owner?.name ?? 'No owner'}</dd>
              </div>
              <div>
                <dt>Lifecycle Stage</dt>
                <dd>{lifecycleLabel}</dd>
              </div>
              <div>
                <dt>Lead Status</dt>
                <dd>{leadStatusLabel}</dd>
              </div>
              <div>
                <dt>Job Title</dt>
                <dd>{contact.jobTitle || '--'}</dd>
              </div>
              <div>
                <dt>Next task</dt>
                <dd>{nextTask ?? 'No open tasks'}</dd>
              </div>
            </dl>
          </Section>

          <Section
            id="companies"
            title={`Companies (${contact.companies.length})`}
            open={isOpen('companies')}
            onToggle={toggle}
          >
            {contact.companies.length ? (
              <div className="ix-sec__b">
                {contact.companies.map((co) => (
                  <div key={co.id} className="ix-ac">
                    <p className="ix-ac__n">
                      <span className="ix-av ix-av--xs" aria-hidden="true">
                        {ixInitials(co.name)}
                      </span>{' '}
                      <Link href={`/companies/${co.id}`}>{co.name}</Link>
                    </p>
                    {co.domain ? (
                      <p>
                        Company domain:{' '}
                        <a
                          className="link"
                          href={`https://${co.domain}`}
                          target="_blank"
                          rel="noreferrer"
                        >
                          {co.domain}
                        </a>
                      </p>
                    ) : null}
                  </div>
                ))}
              </div>
            ) : (
              <Empty text="See the businesses or organizations associated with this record." />
            )}
          </Section>

          {past ? (
            <Section
              id="past"
              title={`Conversations (${past.length}${pastHasMore ? '+' : ''})`}
              open={isOpen('past')}
              onToggle={toggle}
            >
              {past.length ? (
                <div className="ix-sec__b">
                  {past.map((t) => (
                    <div key={t.id} className="ix-ac">
                      <p className="ix-ac__n">
                        <button
                          type="button"
                          className="ix-link"
                          onClick={() => onOpenConversation(t.id)}
                        >
                          {t.subject || '(no subject)'}
                        </button>
                      </p>
                      <p>{messageTime(t.lastMessageAt)}</p>
                    </div>
                  ))}
                  {pastHasMore ? (
                    <Link className="ix-viewall" href={`/contacts/${contact.id}`}>
                      View all on the contact record
                    </Link>
                  ) : null}
                </div>
              ) : (
                <Empty text={`No other conversations with this contact in ${pastScope}.`} />
              )}
            </Section>
          ) : null}
        </>
      )}

      <Section
        id="tickets"
        title={`Tickets (${tickets.length})`}
        open={isOpen('tickets')}
        onToggle={toggle}
      >
        {tickets.length ? (
          <div className="ix-sec__b">
            {tickets.map((tk) => (
              <div key={tk.id} className="ix-ac">
                <p className="ix-ac__n">
                  <Link href={objectRecordPath('ticket', tk.id)}>{tk.name || '(no name)'}</Link>
                  {tk.fromConversation ? (
                    <span className="ix-tag ix-tag--l">This conversation</span>
                  ) : null}
                </p>
                <p>Status: {tk.stageName ?? '--'}</p>
                <p>Priority: {tk.priority ?? '--'}</p>
                <p>Create date: {messageTime(tk.createdAt)}</p>
              </div>
            ))}
          </div>
        ) : (
          <Empty text="Track the customer requests associated with this record." />
        )}
      </Section>

      {contact ? (
        <Section
          id="deals"
          title={`Deals (${contact.deals.length})`}
          open={isOpen('deals')}
          onToggle={toggle}
        >
          {contact.deals.length ? (
            <div className="ix-sec__b">
              {contact.deals.map((d) => (
                <div key={d.id} className="ix-ac">
                  <p className="ix-ac__n">
                    <Link href={`/deals/${d.id}`}>{d.name}</Link>
                  </p>
                  <p>Amount: {formatAmount(d.amount, d.currency) ?? '--'}</p>
                  <p>Close date: {shortDate(d.closeDate)}</p>
                  <p>Stage: {d.stage.name}</p>
                </div>
              ))}
            </div>
          ) : (
            <Empty text="Track the revenue opportunities associated with this record." />
          )}
          <p className="ix-sec__e ix-sec__e--l">
            <Link className="ix-link" href={`/contacts/${contact.id}`}>
              + Add deal on the contact record
            </Link>
          </p>
        </Section>
      ) : null}

      <section className="ix-sec">
        <header>
          <span className="ix-sec__t ix-sec__t--plain">Ticket</span>
        </header>
        <div className="ix-sec__e ix-sec__e--l">
          <p>Create a ticket from this conversation.</p>
          <button
            type="button"
            className="ix-pill"
            disabled={!canCreateTicket}
            title={createTicketTitle}
            onClick={onCreateTicket}
          >
            <IxIcon name="ticket" className="ix-i--sm" />
            Create ticket
          </button>
        </div>
      </section>
    </>
  );
}
