'use client';

import { useMemo } from 'react';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useUserDates } from '@/features/activities/useUserDates';
import type { Deal } from '@/features/deals/types';
import { recordMoney } from '@/features/list-page/money';
import { ownerLabelFromCache } from '@/features/owners/labels';
import { useOwners } from '@/features/owners/useOwners';

function formatValue(value: unknown): string {
  if (value === null || value === undefined || value === '') return '—';
  if (typeof value === 'boolean') return value ? 'Yes' : 'No';
  if (Array.isArray(value)) return value.length ? value.join(', ') : '—';
  return String(value);
}

function formatPicklistLabel(value: string | null | undefined): string {
  if (!value) return '—';
  return value.replace(/[_-]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}

/** DL5: the design's record amount (`recordMoney`), as the deal page shows it. */
function formatMoney(amount: string | null, currency: string): string {
  return recordMoney(amount, currency) ?? '—';
}

/** Read-only list of deal properties (design: View all properties). */
export function DealPropertiesModal({
  open,
  onClose,
  deal,
}: {
  open: boolean;
  onClose: () => void;
  deal: Deal;
}) {
  const { owners } = useOwners(open, true);
  // The user's date format (Settings › Preferences), like the board, table and record page.
  const dates = useUserDates();
  const ownerById = useMemo(() => new Map(owners.map((o) => [o.userId, o])), [owners]);
  const rows: Array<{ label: string; value: string }> = [
    { label: 'Deal name', value: deal.name },
    { label: 'Amount', value: formatMoney(deal.amount, deal.currency) },
    { label: 'Currency', value: deal.currency },
    { label: 'Pipeline', value: deal.pipeline.name },
    { label: 'Deal stage', value: deal.stage.name },
    { label: 'Close date', value: deal.closeDate ? dates.date(deal.closeDate) : '—' },
    { label: 'Priority', value: formatPicklistLabel(deal.priority) },
    { label: 'Deal type', value: formatPicklistLabel(deal.dealType) },
    {
      label: 'Deal owner',
      value: ownerLabelFromCache(deal.owner, ownerById),
    },
    { label: 'Win probability', value: `${deal.probability}%` },
    { label: 'Source', value: formatPicklistLabel(deal.source) },
    { label: 'Created', value: dates.date(deal.createdAt) },
    { label: 'Last updated', value: dates.date(deal.updatedAt) },
  ];

  for (const [key, value] of Object.entries(deal.customProperties ?? {})) {
    rows.push({
      label: key.replace(/[_-]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),
      value: formatValue(value),
    });
  }

  return (
    <CrmModal id="dealPropertiesModal" open={open} onClose={onClose}>
      <ModalHeader id="dealPropertiesModal" title="Deal properties" onClose={onClose} />
      <div className="modal__body">
        <div className="company-intelligence-grid-list">
          {rows.map((row) => (
            <div key={row.label}>
              <span>{row.label}</span>
              <strong style={{ overflowWrap: 'anywhere' }}>{row.value}</strong>
            </div>
          ))}
        </div>
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Close
        </button>
      </div>
    </CrmModal>
  );
}
