import type { FunctionalComponent } from 'preact';

import { ActionRow, EmptyState, SectionCard } from '../../core';
import { Button } from '../../core/Button';
import { ElementVariationCard } from './ElementVariationCard';

type ElementVariationBrowserProps = {
  t: (key: string, fallback?: any) => string;
  selectedElement: any;
  variations: any[];
  parentVariationPath?: any[];
  pathLabel?: string;
  atTop?: boolean;
  canEditElementVariations?: boolean;
  onBack: () => void;
  onEdit: () => void;
  onSelectVariation: (variation: any) => void;
  hasChildren: (variation: any) => boolean;
  isVariationPathActive?: (variationPath: any[]) => boolean;
  isVariationPathInActiveBranch?: (variationPath: any[]) => boolean;
};

export const ElementVariationBrowser: FunctionalComponent<ElementVariationBrowserProps> = ({
  t,
  selectedElement,
  variations,
  parentVariationPath,
  pathLabel,
  atTop,
  canEditElementVariations,
  onBack,
  onEdit,
  onSelectVariation,
  hasChildren,
  isVariationPathActive,
  isVariationPathInActiveBranch,
}) => (
  <div className="ask-flex ask-flex-col ask-gap-4">
    <ActionRow align="between" wrap={false} className="ask-px-3 ask-pt-2">
      <Button type="button" variant="ghost" size="sm" onClick={onBack}>
        {t('common.back', 'Back')}
      </Button>

      {atTop && canEditElementVariations ? (
        <Button type="button" variant="ghost" size="sm" onClick={onEdit}>
          {t('common.edit', 'Edit')}
        </Button>
      ) : null}
    </ActionRow>

    {pathLabel ? (
      <div className="ask-px-3 ask-text-[11px] ask-font-medium ask-text-textMuted">
        {pathLabel}
      </div>
    ) : null}

    <div className="ask-px-3 ask-pb-3">
      <SectionCard title={t('elements.variations', 'Variations')} variant="subtle">
        {variations.length === 0 ? (
          <EmptyState dashed={false} title={t('elements.noVariations', 'No variations')} />
        ) : (
          <div className="ask-flex ask-flex-col ask-gap-2">
            {variations.map((variation: any) => {
              const vid = String(variation?.id ?? '');
              const labelRaw = variation?.name ?? vid;
              const label = String(labelRaw || t('elements.variation', 'Variation'));
              const canApply = !hasChildren(variation);
              const cardPath = [...(parentVariationPath ?? []), variation];

              return (
                <ElementVariationCard
                  key={vid || label}
                  t={t}
                  element={selectedElement}
                  variation={variation}
                  variationPath={cardPath}
                  canApply={canApply}
                  isActive={isVariationPathActive?.(cardPath)}
                  isActiveBranch={isVariationPathInActiveBranch?.(cardPath)}
                  onSelect={onSelectVariation}
                />
              );
            })}
          </div>
        )}
      </SectionCard>
    </div>
  </div>
);
