'use client';

import type { RefObject } from 'react';
import type { ComposerWindowHandle } from '@/components/crm/ComposerWindow';
import { DraggablePopup } from '@/components/crm/DraggablePopup';

/**
 * The design's dialer. Calling from the CRM (Twilio) is not part of go-live (product decision,
 * 25 Nov 2026: logging calls is enough for now), so instead of a dialer drawn turned off it shows
 * the number to call from the rep's own phone (a tel: link) and a way to log the call.
 * EV19: without `composer` (the event record page has no floating composer window), it opens as
 * the page's centred activity popup.
 */
export function CallDialerDrawer({
  open,
  onClose,
  recordName,
  phone,
  composer,
  onLogCall,
}: {
  open: boolean;
  onClose: () => void;
  recordName: string;
  phone?: string | null;
  composer?: RefObject<ComposerWindowHandle | null>;
  /** Opens Log a call for the same record. */
  onLogCall?: () => void;
}) {
  const number = phone?.trim() ?? '';
  return (
    <DraggablePopup
      composer={composer}
      id="contactDialer"
      open={open}
      onClose={onClose}
      title="Call"
    >
      <div className="acx-dialer">
        <div className="acx-dialer__who">
          <strong>{recordName}</strong>
        </div>
        <div className="acx-field">
          <span className="acx-field__label">Phone number</span>
          {number ? (
            <a className="acx-input" href={`tel:${number.replace(/[^\d+]/g, '')}`}>
              {number}
            </a>
          ) : (
            <span className="acx-input">No phone number on this record</span>
          )}
        </div>
        <p className="acx-field__label">
          {onLogCall
            ? 'Call from your phone, then log the call here so it shows on the timeline.'
            : 'Call from your phone, then log the call on the record so it shows on the timeline.'}
        </p>
        {onLogCall ? (
          <button type="button" className="acx-btn acx-btn--call" onClick={onLogCall}>
            <svg
              viewBox="0 0 24 24"
              aria-hidden
              className="iconSize-18"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.7 2z" />
            </svg>
            Log call
          </button>
        ) : null}
      </div>
    </DraggablePopup>
  );
}
