'use client';

import { useCallback, useEffect, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { CollapsibleCard } from '@/features/contacts/ui/CollapsibleCard';
import { formatStamp } from '@/features/objects/record/fields';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  getContactSubscriptionHistory,
  getContactSubscriptions,
  setContactSubscription,
  type ContactSubscriptionChange,
  type ContactSubscriptions,
  type ContactSubscriptionStatus,
} from '../api.client';

/** CS1: the status labels of HubSpot's "Subscription status" drawer. */
const STATUS_LABEL: Record<ContactSubscriptionStatus, string> = {
  subscribed: 'Subscribed',
  unsubscribed: 'Unsubscribed',
  not_set: 'Not Specified',
};

const SOURCE_LABEL: Record<ContactSubscriptionChange['source'], string> = {
  contact: 'Contact',
  user: 'CRM user',
  import: 'Import',
  api: 'API',
};

/** CS1: the row buttons, for each status the row isn't in already. */
const ACTIONS: Array<{ status: ContactSubscriptionStatus; label: string }> = [
  { status: 'unsubscribed', label: 'Unsubscribe' },
  { status: 'subscribed', label: 'Subscribe' },
];

const NONE = '--';
const DRAWER_ID = 'contactSubscriptionsModal';

/**
 * "Communication subscriptions" on the contact page and the Contacts preview (HUB-321; CS1:
 * built to the user's HubSpot screenshots, 19 Nov): a note and "View subscriptions", which opens
 * the "Subscription status" drawer with the contact's choice per type and its change history.
 */
export function ContactSubscriptionsCard({
  contactId,
  canEdit,
}: {
  contactId: string;
  canEdit: boolean;
}) {
  const [open, setOpen] = useState(false);
  return (
    <CollapsibleCard title="Communication subscriptions" cardId="communication-subscriptions">
      <div className="crm-sidebar-info-card">
        <p className="crm-sub-note">
          <span className="crm-sub-note__dot" aria-hidden="true" />
          Use subscription types to manage the communications this contact receives from you
        </p>
        <button
          type="button"
          className="crm-sub-note__link"
          aria-haspopup="dialog"
          onClick={() => setOpen(true)}
        >
          View subscriptions
        </button>
      </div>
      {open ? (
        <SubscriptionStatusDrawer
          contactId={contactId}
          canEdit={canEdit}
          onClose={() => setOpen(false)}
        />
      ) : null}
    </CollapsibleCard>
  );
}

type Tab = 'subscriptions' | 'history';

/** CS1: "Subscription status" (HubSpot): Subscriptions and History tabs. */
function SubscriptionStatusDrawer({
  contactId,
  canEdit,
  onClose,
}: {
  contactId: string;
  canEdit: boolean;
  onClose: () => void;
}) {
  const toast = useToast();
  const { regionFormat, timeZone } = useUserPrefs();
  const [tab, setTab] = useState<Tab>('subscriptions');
  const [subs, setSubs] = useState<ContactSubscriptions | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState<string | null>(null);
  /** Loaded the first time History opens; null until then. */
  const [history, setHistory] = useState<ContactSubscriptionChange[] | null>(null);
  const [historyError, setHistoryError] = useState<string | null>(null);

  const loadHistory = useCallback(
    () =>
      getContactSubscriptionHistory(contactId).then(
        (rows) => {
          setHistory(rows);
          setHistoryError(null);
        },
        (err: unknown) => setHistoryError(errorText(err)),
      ),
    [contactId],
  );

  useEffect(() => {
    let live = true;
    getContactSubscriptions(contactId).then(
      (s) => {
        if (live) setSubs(s);
      },
      (err: unknown) => {
        if (live) setError(errorText(err));
      },
    );
    return () => {
      live = false;
    };
  }, [contactId]);

  const showTab = (next: Tab) => {
    setTab(next);
    if (next === 'history' && history === null) void loadHistory();
  };

  const change = async (typeId: string, status: ContactSubscriptionStatus) => {
    setSaving(typeId);
    try {
      setSubs(await setContactSubscription(contactId, typeId, status));
      toast('Subscription updated', 'success');
      if (history) void loadHistory();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSaving(null);
    }
  };

  const tabs: Array<{ id: Tab; label: string }> = [
    { id: 'subscriptions', label: 'Subscriptions' },
    { id: 'history', label: 'History' },
  ];

  return (
    <CrmModal id={DRAWER_ID} open onClose={onClose} drawer className="crm-subs-drawer">
      <ModalHeader id={DRAWER_ID} title="Subscription status" onClose={onClose} />
      <div className="modal__body">
        <div className="crm-subs-tabs" role="tablist" aria-label="Subscription status">
          {tabs.map((t) => (
            <button
              key={t.id}
              type="button"
              role="tab"
              id={`${DRAWER_ID}-tab-${t.id}`}
              aria-selected={tab === t.id}
              aria-controls={`${DRAWER_ID}-panel-${t.id}`}
              className={cn('crm-subs-tabs__tab', tab === t.id && 'is-active')}
              onClick={() => showTab(t.id)}
            >
              {t.label}
            </button>
          ))}
        </div>

        {tab === 'subscriptions' ? (
          <div
            role="tabpanel"
            id={`${DRAWER_ID}-panel-subscriptions`}
            aria-labelledby={`${DRAWER_ID}-tab-subscriptions`}
          >
            {error ? <p className="crm-text-danger crm-fs-7">{error}</p> : null}
            {subs === null && !error ? <p className="crm-fs-7">Loading…</p> : null}
            {subs?.globallyBlocked ? (
              <p className="crm-fs-7">
                <strong>
                  {subs.emailStatus === 'bounced'
                    ? 'This address bounced.'
                    : 'Unsubscribed from all email.'}
                </strong>{' '}
                No automated email of any type is sent to it.
              </p>
            ) : null}
            {subs && !subs.email ? (
              <p className="crm-fs-7">This contact has no email address.</p>
            ) : null}
            {subs ? (
              <table className="crm-subs-table">
                <thead>
                  <tr>
                    <th scope="col">Channel</th>
                    <th scope="col">Subscription type</th>
                    <th scope="col">
                      <span className="crm-subs-sr">Actions</span>
                    </th>
                    <th scope="col">Status</th>
                  </tr>
                </thead>
                <tbody>
                  {subs.data.map((s) => (
                    <tr key={s.type.id} className="crm-subs-table__row">
                      <td>Email</td>
                      <td>
                        {s.type.name}
                        {s.type.active ? '' : ' (inactive)'}
                      </td>
                      <td className="crm-subs-table__acts">
                        {canEdit
                          ? ACTIONS.filter((a) => a.status !== s.status).map((a) => (
                              <button
                                key={a.status}
                                type="button"
                                className="crm-subs-pill"
                                disabled={saving !== null}
                                aria-label={`${a.label}: ${s.type.name}`}
                                onClick={() => void change(s.type.id, a.status)}
                              >
                                {a.label}
                              </button>
                            ))
                          : null}
                      </td>
                      <td>
                        <StatusCell status={s.status} />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : null}
          </div>
        ) : (
          <div
            role="tabpanel"
            id={`${DRAWER_ID}-panel-history`}
            aria-labelledby={`${DRAWER_ID}-tab-history`}
          >
            {historyError ? <p className="crm-text-danger crm-fs-7">{historyError}</p> : null}
            {history === null && !historyError ? <p className="crm-fs-7">Loading…</p> : null}
            {history ? (
              <div className="crm-subs-scroll">
                <table className="crm-subs-table crm-subs-table--history">
                  <thead>
                    <tr>
                      <th scope="col">Channel</th>
                      <th scope="col">Subscription</th>
                      <th scope="col">New status</th>
                      <th scope="col">Contact Info</th>
                      <th scope="col">Legal basis</th>
                      <th scope="col">Explanation</th>
                      <th scope="col">Requested by</th>
                      <th scope="col">Source</th>
                      <th scope="col">Date</th>
                    </tr>
                  </thead>
                  <tbody>
                    {history.length ? (
                      history.map((h, i) => (
                        <tr key={`${h.typeId}-${h.changedAt}-${i}`}>
                          <td>Email</td>
                          <td>{h.typeName || NONE}</td>
                          <td>{STATUS_LABEL[h.status]}</td>
                          <td>{NONE}</td>
                          <td>{NONE}</td>
                          <td>{NONE}</td>
                          <td>{h.changedBy?.name ?? NONE}</td>
                          <td>{SOURCE_LABEL[h.source]}</td>
                          <td>{formatStamp(h.changedAt, { region: regionFormat, timeZone })}</td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan={9} className="crm-subs-table__empty">
                          There aren&apos;t any subscription changes for this contact.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            ) : null}
          </div>
        )}
      </div>
    </CrmModal>
  );
}

function StatusCell({ status }: { status: ContactSubscriptionStatus }) {
  return (
    <span className="crm-subs-status">
      <span className={cn('crm-subs-status__dot', `is-${status}`)} aria-hidden="true" />
      {STATUS_LABEL[status]}
      <span className="crm-subs-status__info" title="Subscription status">
        <CrmIcon name="info" className="iconSize-14" />
      </span>
    </span>
  );
}
