'use client';

import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import type { Company } from '@/features/companies/types';
import { MERGED_IDS_LABEL, mergedIdsText } from '@/features/duplicates/mergedIds';

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());
}

function formatDate(iso: string | null | undefined): string {
  if (!iso) return '—';
  try {
    return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' }).format(new Date(iso));
  } catch {
    return iso.slice(0, 10);
  }
}

/**
 * Read-only list of company properties from the API payload (design: View all properties).
 * Employees / annual revenue / type are omitted when the API does not return them.
 */
export function CompanyPropertiesModal({
  open,
  onClose,
  company,
  industryLabel,
}: {
  open: boolean;
  onClose: () => void;
  company: Company;
  industryLabel: string;
}) {
  const location = [company.city, company.state, company.country].filter(Boolean).join(', ') || '—';

  const rows: Array<{ label: string; value: string }> = [
    { label: 'Company name', value: company.name },
    { label: 'Domain', value: company.domain ?? '—' },
    { label: 'Website', value: company.website ?? '—' },
    { label: 'Phone', value: company.phone ?? '—' },
    { label: 'Industry', value: industryLabel },
    { label: 'City / location', value: location },
    {
      label: 'Company owner',
      value: company.owner ? `${company.owner.name} (${company.owner.email})` : 'Unassigned',
    },
    { label: 'Source', value: formatPicklistLabel(company.source) },
    { label: 'Created', value: formatDate(company.createdAt) },
    { label: 'Last updated', value: formatDate(company.updatedAt) },
    // G18: the companies merged into this one.
    { label: MERGED_IDS_LABEL.company, value: mergedIdsText(company.mergedIds) || '—' },
  ];

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

  return (
    <CrmModal id="companyPropertiesModal" open={open} onClose={onClose}>
      <ModalHeader id="companyPropertiesModal" title="Company 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>
  );
}
