import React from 'react';
import { Box, Text, Divider, Tooltip } from '@wix/design-system';
import { ChevronRight, ChevronDown, ChevronUp } from '@wix/wix-ui-icons-common';
import { SetupWidgetStep } from '@wix/bex-core';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { SetupStepIcon } from './SetupStepIcon';
import { st, classes } from './SetupWidget.st.css.js';

export interface SetupStepCardProps {
  step: SetupWidgetStep;
  /** The recommended next step — soft blue surface + bold title. */
  isPrimary: boolean;
  /** Inline content is shown below the header. */
  expanded: boolean;
  onActivate: () => void;
  renderStepContent?: (step: SetupWidgetStep) => React.ReactNode;
}

/**
 * Mobile step card (per Figma "Support FW on mobile"). 12px padding, a 24px
 * icon cell and a trailing chevron that replaces the per-step CTA button: a
 * right chevron for navigate / completed (with a completed action) steps, and a
 * down/up chevron for inline-expandable steps. The whole card is the click
 * target. Collapsed cards are a bare title + chevron; an expanded inline card
 * adds a divider, its description, and the consumer content below the header.
 */
export const SetupStepCard = ({
  step,
  isPrimary,
  expanded,
  onActivate,
  renderStepContent,
}: SetupStepCardProps) => {
  const { translate: t } = useWixPatternsContainer();

  const isInProgress = step.status === 'in-progress';
  const isCompleted = step.status === 'completed';
  const isDisabled = step.status === 'disabled';
  const isInline = step.expansionMode === 'inline';
  const isInlineExpanded = expanded && isInline;

  // Completed steps stay actionable only when they carry a completed action.
  const showCompletedCta =
    isCompleted && !!step.completedCtaLabel && !isDisabled;
  // Inline steps toggle; navigate steps act; completed steps fire their action.
  const isTogglable = isInline && !isCompleted && !isDisabled;
  const isNavigable = !isInline && !isCompleted && !isDisabled;
  const clickable = isTogglable || isNavigable || showCompletedCta;

  // Disabled steps show a muted chevron (with a permission tooltip); completed
  // steps without an action show none. Everything actionable shows a chevron.
  const showChevron = clickable || isDisabled;

  const ChevronIcon = isInline
    ? isInlineExpanded
      ? ChevronUp
      : ChevronDown
    : ChevronRight;

  const chevron = showChevron && (
    <Box
      dataHook={`setup-step-cta-${step.id}`}
      verticalAlign="middle"
      className={st(isDisabled ? classes.chevronDisabled : classes.chevron)}
    >
      <ChevronIcon width="18" height="18" />
    </Box>
  );

  // The description only belongs to the expanded inline state. Non-inline steps
  // keep theirs (if provided) inline below the header.
  const description = step.description && !isCompleted && (
    <Text size="small" secondary>
      {step.description}
    </Text>
  );

  return (
    <div
      data-hook={`setup-step-${step.id}`}
      data-focused={isPrimary}
      className={st(classes.card, { primary: isPrimary, clickable })}
      onClick={clickable ? onActivate : undefined}
      role={clickable ? 'button' : undefined}
      tabIndex={clickable ? 0 : undefined}
      onKeyDown={
        clickable
          ? (event: React.KeyboardEvent) => {
              if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                onActivate();
              }
            }
          : undefined
      }
    >
      <Box direction="vertical" gap="SP2" padding="SP2">
        <Box
          align="space-between"
          verticalAlign="middle"
          gap="SP1"
          width="100%"
        >
          <Box verticalAlign="middle" gap="SP1" flexGrow={1} minWidth={0}>
            <Box className={st(classes.stepIcon)}>
              <SetupStepIcon status={step.status} marginTop="0px" />
            </Box>
            {/* Title + "In progress" badge stack together so the icon centers
                against the whole block (matches the Figma in-progress card). */}
            <Box direction="vertical" gap="SP1">
              <Text
                dataHook={`setup-step-title-${step.id}`}
                size="small"
                weight={isPrimary ? 'bold' : 'thin'}
                skin={isDisabled ? 'disabled' : 'standard'}
                secondary={isCompleted}
              >
                {isCompleted ? <del>{step.title}</del> : step.title}
              </Text>
              {isInProgress && (
                <Text
                  size="tiny"
                  weight="normal"
                  className={st(classes.inProgressLabel)}
                >
                  {t('cairo.setupWidget.step.inProgress')}
                </Text>
              )}
            </Box>
          </Box>
          {isDisabled ? (
            <Tooltip
              dataHook={`setup-step-disabled-tooltip-${step.id}`}
              content={
                step.disabledTooltip ??
                // Translation-key id stays `lockedTooltip` until the
                // Translation Center key is renamed (TC follow-up to T2).
                t('cairo.setupWidget.step.lockedTooltip')
              }
            >
              {chevron}
            </Tooltip>
          ) : (
            chevron
          )}
        </Box>

        {/* Expanded inline step: a divider separates the header from the
            description and the consumer-supplied content. */}
        {isInlineExpanded && (
          <>
            <Divider />
            {description}
            <Box
              dataHook={`setup-step-content-${step.id}`}
              direction="vertical"
            >
              {/* Stop clicks/keys inside the consumer widget from bubbling to
                  the card's toggle handler — otherwise interacting with the
                  content (e.g. an input) would collapse the card. */}
              <div
                onClick={(event) => event.stopPropagation()}
                onKeyDown={(event) => event.stopPropagation()}
              >
                {renderStepContent?.(step)}
              </div>
            </Box>
          </>
        )}

        {/* Non-inline steps render their description (if any) under the row. */}
        {!isInline && description}
      </Box>
    </div>
  );
};
