import { cva } from 'class-variance-authority'
import { SvgCheck } from '@chainlink/blocks-icons'
import { cn } from '../../../utils'
import { Typography } from '../../Typography'
import type { Status } from './ProgressBar'

export type Step = { label: string; status: Status }

export type ProgressBarStepProps = Step & {
  index: number
  lastStepIndex: number
}

const markerVariants = cva(
  'inline-flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-full text-xs font-semibold',
  {
    variants: {
      status: {
        DONE: 'bg-stepper-counter-done text-stepper-counter-foreground',
        ACTIVE: 'bg-stepper-counter-active text-stepper-counter-foreground',
        IN_PROGRESS:
          'bg-stepper-counter-active text-stepper-counter-foreground',
        ERROR: 'bg-stepper-counter-error text-stepper-counter-foreground',
        PENDING:
          'bg-stepper-counter-pending-background text-stepper-counter-pending-foreground',
      },
    },
  },
)

const labelVariants = cva('', {
  variants: {
    status: {
      DONE: 'text-stepper-counter-done',
      ACTIVE: 'text-stepper-counter-active',
      IN_PROGRESS: 'text-stepper-counter-active',
      ERROR: 'text-error-foreground',
      PENDING: 'text-muted-foreground',
    },
  },
})

export const ProgressBarStep = ({
  label,
  status,
  index,
  lastStepIndex,
}: ProgressBarStepProps) => {
  const isDone = status === 'DONE'
  const isError = status === 'ERROR'
  const isFirstStep = index === 0
  const isLastStep = index === lastStepIndex

  return (
    <div className="relative grid grid-cols-[26px_minmax(0,1fr)] items-center gap-x-2 py-3">
      {!isFirstStep && (
        <span className="absolute bottom-[calc(50%+17px)] left-[13px] top-0 w-px -translate-x-1/2 bg-stepper-counter-track-pending" />
      )}

      {!isLastStep && (
        <span className="absolute bottom-0 left-[13px] top-[calc(50%+17px)] w-px -translate-x-1/2 bg-stepper-counter-track-pending" />
      )}

      <span className={cn(markerVariants({ status }), 'relative z-10')}>
        {isDone ? (
          <SvgCheck color="counter" className="h-3 w-3" />
        ) : isError ? (
          '!'
        ) : (
          index + 1
        )}
      </span>

      <div className="flex min-h-[26px] min-w-0 items-center">
        <Typography
          variant="body-semi-xs"
          className={labelVariants({ status })}
        >
          {label}
        </Typography>
      </div>
    </div>
  )
}
