'use client';

import { useEffect, useMemo, useState } from 'react';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import {
  applyPropertyLogic,
  propertyLogicValues,
  usePropertyLogic,
} from '@/features/custom-properties/logic';
import { listPropertyGroups, type PropertyGroup } from '@/features/data-model/api.client';
import type { CustomProperties } from '@/types/api';
import { CollapsibleCard } from '../CollapsibleCard';
import { CustomFieldsList, type CustomFieldsEdit } from './custom-fields';

const OTHER = '';

/** "media_intelligence" → "Media intelligence", for a group the API didn't return. */
function groupLabelFromName(name: string): string {
  const text = name.replace(/[_-]+/g, ' ').trim();
  return text ? text.charAt(0).toUpperCase() + text.slice(1) : 'Other properties';
}

/**
 * HUB-615: the record's custom fields as one sidebar card per property group (HubSpot's
 * "Media Intelligence", "Key info"…), in the groups' order, each value edited in place.
 * Cards start closed so a record with hundreds of migrated fields stays short.
 */
export function PropertyGroupCards({
  objectType,
  defs,
  values,
  builtIns,
  edit,
  onHistory,
}: {
  objectType: 'contact' | 'company' | 'deal';
  defs: CustomPropertyDefinition[];
  values: CustomProperties;
  /** The record's built-in values field rules may read (lead status, deal stage…). */
  builtIns?: Record<string, unknown>;
  edit: CustomFieldsEdit;
  /** HUB-356: open a field's property history (gets the field's name). */
  onHistory?: (name: string) => void;
}) {
  const [groups, setGroups] = useState<PropertyGroup[]>([]);
  /**
   * GLB4 (go-live Medium 5): the cards wait for the groups, so a card's title never shows its raw
   * name ("Admedia ai") before the group's label. A failed load still shows the built names.
   */
  const [groupsLoaded, setGroupsLoaded] = useState(false);
  useEffect(() => {
    let cancelled = false;
    listPropertyGroups({ objectType }).then(
      (list) => {
        if (cancelled) return;
        setGroups(list);
        setGroupsLoaded(true);
      },
      () => {
        if (cancelled) return;
        setGroups([]);
        setGroupsLoaded(true);
      },
    );
    return () => {
      cancelled = true;
    };
  }, [objectType]);

  // HUB-355: hide dependent fields whose condition isn't met, across all groups.
  const rules = usePropertyLogic(objectType);
  const shown = applyPropertyLogic(
    defs,
    rules,
    propertyLogicValues(objectType, builtIns ?? {}, values),
  );

  const cards = useMemo(() => {
    const byGroup = new Map<string, CustomPropertyDefinition[]>();
    for (const def of shown) {
      const key = def.groupName ?? OTHER;
      byGroup.set(key, [...(byGroup.get(key) ?? []), def]);
    }
    const known = [...groups]
      .filter((g) => !g.archived && byGroup.has(g.name))
      .sort((a, b) => a.displayOrder - b.displayOrder)
      .map((g) => ({ key: g.name, label: g.label }));
    const knownKeys = new Set(known.map((g) => g.key));
    const rest = [...byGroup.keys()]
      .filter((key) => !knownKeys.has(key) && key !== OTHER)
      .sort()
      .map((key) => ({ key, label: groupLabelFromName(key) }));
    const other = byGroup.has(OTHER) ? [{ key: OTHER, label: 'Other properties' }] : [];
    return [...known, ...rest, ...other].map((g) => ({ ...g, defs: byGroup.get(g.key) ?? [] }));
  }, [shown, groups]);

  if (!groupsLoaded) return null;
  return (
    <>
      {cards.map((card) => (
        <CollapsibleCard
          key={card.key || 'other'}
          title={card.label}
          cardId={`group-${card.key || 'other'}`}
          defaultOpen={false}
          action={<span className="crm-collapsible-card__count">{card.defs.length}</span>}
        >
          <div className="crm-about-contact">
            <CustomFieldsList defs={card.defs} values={values} edit={edit} onHistory={onHistory} />
          </div>
        </CollapsibleCard>
      ))}
    </>
  );
}
