'use client'

import * as React from 'react'
import * as CheckboxPrimitive from '@radix-ui/react-checkbox'
import { CheckIcon } from 'lucide-react'
import { cn } from '@/lib/utils'
import { cva, type VariantProps } from 'class-variance-authority'

const checkboxVariants = cva(
  'peer shrink-0 border shadow-sm transition-all outline-none flex justify-center items-center',
  {
    variants: {
      size: {
        sm: 'size-4',
        lg: 'size-5',
      },
      variant: {
        default: '',
        contrast: 'border-2',
      },
      shape: {
        square: 'rounded-[4px]',
        round: 'rounded-full',
      },
    },
    defaultVariants: {
      size: 'lg',
      variant: 'default',
      shape: 'square',
    },
  }
)

const iconVariants = cva('flex items-center justify-center text-current transition-all', {
  variants: {
    size: {
      sm: 'size-3',
      lg: 'size-4',
    },
  },
  defaultVariants: {
    size: 'lg',
  },
})

interface CheckboxProps
  extends
    React.ComponentProps<typeof CheckboxPrimitive.Root>,
    VariantProps<typeof checkboxVariants> {
  error?: boolean
}

function Checkbox({ className, size, variant, shape, error, ...props }: CheckboxProps) {
  return (
    <CheckboxPrimitive.Root
      className={cn(
        checkboxVariants({ size, variant, shape }),
        // 未选中状态
        'border-outline-normal bg-surface-element-normal',
        // 选中状态
        'data-[state=checked]:bg-primary-normal data-[state=checked]:border-primary-normal',
        // 悬浮状态
        'hover:bg-surface-element-hover hover:border-outline-hover',
        'hover:data-[state=checked]:bg-primary-hover hover:data-[state=checked]:border-primary-hover',
        // 按下状态
        'active:bg-surface-element-press active:border-outline-press',
        'active:data-[state=checked]:bg-primary-press active:data-[state=checked]:border-primary-press',
        // 禁用状态
        'disabled:bg-surface-element-disabled disabled:border-outline-disabled',
        'disabled:data-[state=checked]:bg-primary-disabled disabled:data-[state=checked]:border-primary-disabled',
        'disabled:cursor-not-allowed disabled:opacity-30',
        // 错误状态
        error && 'border-important-normal',
        // 聚焦状态
        'focus-visible:ring-outline-normal focus-visible:ring-2 focus-visible:outline-none',
        className
      )}
      {...props}
    >
      <CheckboxPrimitive.Indicator
        className={cn(iconVariants({ size }), 'text-txt-primary-normal')}
      >
        <CheckIcon className={cn('size-full')} />
      </CheckboxPrimitive.Indicator>
    </CheckboxPrimitive.Root>
  )
}

export { Checkbox }
