import React from 'react';
import {
  Box,
  Text,
  Button,
  TextButton,
  Badge,
  Divider,
  Tooltip,
} from '@wix/design-system';
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 SetupStepRowProps {
  step: SetupWidgetStep;
  /** Highlighted + bold row (the recommended (primary) or expanded step). */
  isFocused: boolean;
  /** Inline content is shown below the row. */
  expanded: boolean;
  onActivate: () => void;
  /** Supplies the inline-expansion content (render prop on the widget). */
  renderStepContent?: (step: SetupWidgetStep) => React.ReactNode;
}

/**
 * Desktop step row. Recreated from the existing Setup widget:
 * - completed → green check, struck-through title, optional completed CTA
 * - disabled → muted bullet + disabled CTA (permission-denied)
 * - in-progress → "In progress" badge next to the title
 * - focused → blue surface, bold title, primary CTA
 * - hoverable rows tint blue on hover (handled in Stylable)
 */
export const SetupStepRow = ({
  step,
  isFocused,
  expanded,
  onActivate,
  renderStepContent,
}: SetupStepRowProps) => {
  const { translate: t } = useWixPatternsContainer();

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

  const showCta = !isCompleted && !!step.ctaLabel && !isInlineExpanded;
  // Completed steps stay actionable when they carry a completed CTA (G2).
  const showCompletedCta = isCompleted && !!step.completedCtaLabel && !isDisabled;
  const clickable = (!isCompleted && !isDisabled) || showCompletedCta;
  const hoverable = !isFocused && !isCompleted && !isDisabled;

  const handleClick = clickable ? onActivate : undefined;

  return (
    <div
      data-hook={`setup-step-${step.id}`}
      data-focused={isFocused}
      className={st(classes.row, {
        focused: isFocused,
        hoverable,
        clickable,
      })}
      onClick={handleClick}
      onKeyDown={
        clickable
          ? (event: React.KeyboardEvent) => {
              if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                onActivate();
              }
            }
          : undefined
      }
      role={clickable ? 'button' : undefined}
      tabIndex={clickable ? 0 : undefined}
    >
      {/* Reserve the CTA button's height (small button = 30px) so rows keep a
          stable height whether or not they render a CTA — otherwise completed
          rows (which drop the CTA) would shrink and the widget would reflow. */}
      <Box
        align="space-between"
        verticalAlign="middle"
        width="100%"
        minHeight="30px"
      >
        <Box minHeight="24px" verticalAlign="middle">
          <SetupStepIcon status={step.status} />
          <Box
            paddingLeft="SP2"
            paddingRight="SP2"
            verticalAlign="middle"
            gap="SP1"
          >
            <Text
              dataHook={`setup-step-title-${step.id}`}
              size="small"
              skin={isDisabled ? 'disabled' : 'standard'}
              weight={isFocused ? 'bold' : 'thin'}
              secondary={isCompleted}
              light={isCompleted}
            >
              {isCompleted ? <del>{step.title}</del> : step.title}
            </Text>
            {isInProgress && !isInlineExpanded && (
              <Box marginTop="2px">
                <Badge size="tiny" skin="urgent" type="transparent">
                  {t('cairo.setupWidget.step.inProgress')}
                </Badge>
              </Box>
            )}
          </Box>
        </Box>
        {showCta &&
          (() => {
            const ctaNode = (
              <Box verticalAlign="middle">
                <Button
                  dataHook={`setup-step-cta-${step.id}`}
                  size="small"
                  priority={!isDisabled && !isFocused ? 'secondary' : 'primary'}
                  disabled={isDisabled}
                  ellipsis={false}
                  onClick={(event: React.MouseEvent) => {
                    event.stopPropagation();
                    onActivate();
                  }}
                >
                  {step.ctaLabel}
                </Button>
              </Box>
            );

            // Disabled steps explain why the CTA is disabled (G5).
            return 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')
                }
              >
                {ctaNode}
              </Tooltip>
            ) : (
              ctaNode
            );
          })()}
        {showCompletedCta && (
          <Box
            verticalAlign="middle"
            marginRight="SP2"
            className={st(classes.completedCta)}
          >
            <TextButton
              dataHook={`setup-step-cta-${step.id}`}
              size="small"
              onClick={(event: React.MouseEvent) => {
                event.stopPropagation();
                onActivate();
              }}
            >
              {step.completedCtaLabel}
            </TextButton>
          </Box>
        )}
      </Box>
      {isInlineExpanded && (
        <Box
          dataHook={`setup-step-content-${step.id}`}
          direction="vertical"
          paddingLeft="SP5"
          paddingRight="SP1"
          paddingBottom="SP1"
          marginTop="SP2"
        >
          <Box marginBottom="SP2">
            <Divider />
          </Box>
          {/* Stop clicks/keys inside the consumer widget from bubbling to the
              row'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>
      )}
    </div>
  );
};
