'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/cn'

export interface CheckboxProps
  extends Omit<React.ComponentProps<typeof CheckboxPrimitive.Root>, 'children'> {
  label?: string
  containerClass?: string
  labelClass?: string
  hasError?: boolean
  errorMessage?: string
}

export const Checkbox = React.forwardRef<
  React.ElementRef<typeof CheckboxPrimitive.Root>,
  CheckboxProps
>(
  (
    { label, containerClass, labelClass, className, hasError = false, errorMessage, ...props },
    ref,
  ) => {
    const id = React.useId()
    const baseStyles = [
      'flex items-center justify-center',
      'w-5 h-5 min-w-[20px] rounded',
      hasError ? 'border border-func-red-main dark:border-red' : 'border-transparent',
      'bg-neutral-700 hover:bg-neutral-500 focus:bg-neutral-700',
      'focus:outline-none focus:ring-2 focus:ring-ring/50',
      'disabled:cursor-not-allowed disabled:opacity-50',
      'transition-[background-color,border-color,box-shadow] duration-150',
      'data-[state=checked]:bg-[#d39e7f]',
    ]

    return (
      <div className={cn('flex flex-col items-start', containerClass)}>
        <div className="flex items-center">
          <CheckboxPrimitive.Root
            id={id}
            data-slot="checkbox"
            ref={ref}
            className={cn(...baseStyles, className)}
            {...props}
          >
            <CheckboxPrimitive.Indicator
              data-slot="checkbox-indicator"
              className="flex items-center justify-center"
            >
              <CheckIcon className="w-4 h-4 text-white" />
            </CheckboxPrimitive.Indicator>
          </CheckboxPrimitive.Root>

          {label && (
            <label
              htmlFor={id}
              className={cn(
                'ml-3 text-[#b8b7b5] cursor-pointer text-base leading-[1.24]',
                labelClass,
              )}
            >
              {label}
            </label>
          )}
        </div>
        {hasError && errorMessage && (
          <p className="text-func-red-main text-xs mt-1">{errorMessage}</p>
        )}
      </div>
    )
  },
)

Checkbox.displayName = 'Checkbox'
