import type { FunctionalComponent } from 'preact';

import { Badge } from '../../core';
import { resolveElementVariationPreview } from '../../../core/elementVariationPreview';

type ElementVariationCardProps = {
  t: (key: string, fallback?: any) => string;
  element: any;
  variation: any;
  variationPath?: any[];
  canApply?: boolean;
  isActive?: boolean;
  isActiveBranch?: boolean;
  onSelect: (variation: any) => void;
};

export const ElementVariationCard: FunctionalComponent<ElementVariationCardProps> = ({ t, variation, variationPath, canApply, isActive, isActiveBranch, onSelect }) => {
  const vid = String(variation?.id ?? '');
  const labelRaw = variation?.name ?? vid;
  const label = String(labelRaw || t('elements.variation', 'Variation'));
  const preview = resolveElementVariationPreview(variation, variationPath);
  const childCount = Array.isArray(variation?.variations) ? variation.variations.length : 0;

  return (
    <button
      key={vid || label}
      type="button"
      className={`ask-w-full ask-text-left ask-flex ask-items-center ask-justify-between ask-gap-2 ask-rounded-xl ask-border ask-p-2 hover:ask-bg-surface ${isActive ? 'ask-border-primary/50 ask-bg-primary/10' : isActiveBranch ? 'ask-border-primary/30 ask-bg-primary/5' : 'ask-border-borderSubtle ask-bg-surfaceAlt'}`}
      onClick={() => onSelect(variation)}
    >
      <div className="ask-flex ask-items-center ask-gap-2 ask-min-w-0">
        <div className="ask-h-9 ask-w-9 ask-rounded-md ask-border ask-border-borderSubtle ask-bg-surface ask-overflow-hidden ask-flex ask-items-center ask-justify-center">
          {preview.kind === 'image' ? (
            <img src={preview.value} alt="" className="ask-h-full ask-w-full ask-object-contain" />
          ) : preview.kind === 'texture' ? (
            <img src={preview.value} alt="" className="ask-h-full ask-w-full ask-object-cover" />
          ) : (
            <span className="ask-h-full ask-w-full" style={{ background: preview.value }} />
          )}
        </div>
        <div className="ask-min-w-0">
          <div className="ask-flex ask-min-w-0 ask-items-center ask-gap-2">
            <span className="ask-truncate ask-font-medium ask-text-textMain">{label}</span>
            {isActive ? <Badge variant="primary" size="sm">{t('elements.activeVariation', 'Active')}</Badge> : null}
            {!isActive && isActiveBranch ? <Badge variant="surface" size="sm">{t('elements.currentBranch', 'Current')}</Badge> : null}
          </div>
          <div className="ask-truncate ask-text-[11px] ask-text-textMuted">
            {canApply ? t('elements.apply', 'Apply') : `${t('elements.open', 'Open')}${childCount ? ` · ${childCount}` : ''}`}
          </div>
        </div>
      </div>

      <div className="ask-text-textMuted ask-text-sm">{canApply ? '↵' : '›'}</div>
    </button>
  );
};
