import React from 'react';
import { Box, Text, Badge, Tag } from '@wix/design-system';
import { 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 SetupStepGroupProps {
  step: SetupWidgetStep;
  isMobile: boolean;
  /** The group's children are shown. */
  expanded: boolean;
  /** The recommended/focused row. */
  isPrimary: boolean;
  onToggle: () => void;
  /** Renders a single child step (the parent supplies the row/card). */
  renderChild: (child: SetupWidgetStep) => React.ReactNode;
}

/**
 * Aggregated group row (e.g. "Stores", "Bookings"). Collapsed: icon + title +
 * an "x/y" counter + chevron. Expanded: the children render indented below.
 * Completion / in-progress are derived from the children (mirrors
 * `AggregatedByGroupStep` in dashboard-setup). The toggle lives on the header
 * only, so clicking a child doesn't collapse the group.
 */
export const SetupStepGroup = ({
  step,
  isMobile,
  expanded,
  isPrimary,
  onToggle,
  renderChild,
}: SetupStepGroupProps) => {
  const { translate: t } = useWixPatternsContainer();

  const children = step.steps ?? [];
  const total = children.length;
  const completed = children.filter((c) => c.status === 'completed').length;
  const allCompleted = total > 0 && completed === total;
  const anyInProgress = children.some((c) => c.status === 'in-progress');
  const isFocused = expanded || isPrimary;
  const Chevron = expanded ? ChevronUp : ChevronDown;

  const header = (
    <div
      role="button"
      tabIndex={0}
      onClick={onToggle}
      onKeyDown={(event: React.KeyboardEvent) => {
        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          onToggle();
        }
      }}
      style={{ cursor: 'pointer' }}
    >
      <Box
        align="space-between"
        verticalAlign="middle"
        width="100%"
        minHeight="30px"
      >
        <Box
          minHeight="24px"
          verticalAlign="middle"
          gap={isMobile ? 'SP1' : undefined}
        >
          {isMobile ? (
            <Box className={st(classes.stepIcon)}>
              <SetupStepIcon
                status={allCompleted ? 'completed' : 'upcoming'}
                marginTop="0px"
              />
            </Box>
          ) : (
            <SetupStepIcon status={allCompleted ? 'completed' : 'upcoming'} />
          )}
          {/* Mobile cards stack the badge under the title (matches
              SetupStepCard); desktop rows keep it inline next to it. */}
          <Box
            paddingLeft={isMobile ? undefined : 'SP2'}
            direction={isMobile ? 'vertical' : 'horizontal'}
            verticalAlign={isMobile ? undefined : 'middle'}
            gap="SP1"
          >
            <Text
              dataHook={`setup-step-title-${step.id}`}
              size="small"
              weight={isFocused ? 'bold' : 'thin'}
            >
              {step.title}
            </Text>
            {anyInProgress &&
              !allCompleted &&
              (isMobile ? (
                <Text
                  size="tiny"
                  weight="normal"
                  className={st(classes.inProgressLabel)}
                >
                  {t('cairo.setupWidget.step.inProgress')}
                </Text>
              ) : (
                <Box marginTop="2px">
                  <Badge size="tiny" skin="urgent" type="transparent">
                    {t('cairo.setupWidget.step.inProgress')}
                  </Badge>
                </Box>
              ))}
          </Box>
        </Box>
        <Box verticalAlign="middle" gap="SP1">
          <Tag
            id={`setup-step-counter-${step.id}`}
            skin="neutral"
            removable={false}
            size="small"
          >
            {t('cairo.setupWidget.aggregated.counter', { completed, total })}
          </Tag>
          <Box dataHook={`setup-step-chevron-${step.id}`}>
            <Chevron width="20" height="20" />
          </Box>
        </Box>
      </Box>
    </div>
  );

  const childList = expanded && (
    <Box
      dataHook={`setup-step-children-${step.id}`}
      direction="vertical"
      gap={isMobile ? 'SP3' : 'SP1'}
      paddingLeft="SP5"
      marginTop={isMobile ? 'SP3' : 'SP1'}
    >
      {children.map((child) => (
        <React.Fragment key={child.id}>{renderChild(child)}</React.Fragment>
      ))}
    </Box>
  );

  if (isMobile) {
    return (
      <div data-hook={`setup-step-${step.id}`} className={st(classes.card)}>
        <Box direction="vertical" padding="SP2">
          {header}
          {childList}
        </Box>
      </div>
    );
  }

  return (
    <div data-hook={`setup-step-${step.id}`} className={st(classes.row)}>
      {header}
      {childList}
    </div>
  );
};
