'use client';

import { ChangeEventHandler, FocusEventHandler, ReactNode, useId } from 'react';

import { cn } from '@/lib/helper';
import FieldMessage from '@/components/helper/FieldMessage';

export interface CheckboxInputProps {
  // Basic Props
  name: string;
  label?: string;
  bottomLabel?: string;
  checked?: boolean;
  value?: string | number;
  indeterminate?: boolean;
  naked?: boolean; // New prop for checkbox-only mode

  // Styling Props
  className?: {
    wrapper?: string;
    label?: string;
    checkbox?: string;
    input?: string;
  };

  // State Props
  isError?: boolean;
  isValid?: boolean;
  errorMessage?: string;
  disabled?: boolean;
  readOnly?: boolean;
  required?: boolean;
  isLoading?: boolean;

  // Adornment Props
  startAdornment?: ReactNode;
  endAdornment?: ReactNode;

  // Event Handlers
  onChange?: ChangeEventHandler<HTMLInputElement>;
  onBlur?: FocusEventHandler<HTMLInputElement>;
  onFocus?: FocusEventHandler<HTMLInputElement>;

  // Additional Props
  tooltip?: string;
  description?: string;
  size?: 'sm' | 'md' | 'lg';
  variant?:
    | 'default'
    | 'primary'
    | 'secondary'
    | 'success'
    | 'warning'
    | 'info'
    | 'error';
}

const CheckboxInput = ({
  name,
  label,
  bottomLabel,
  checked = false,
  value,
  indeterminate = false,
  naked = false,
  className,
  isError,
  errorMessage,
  disabled = false,
  readOnly = false,
  required = false,
  isLoading = false,
  startAdornment,
  endAdornment,
  onChange,
  onBlur,
  onFocus,
  tooltip,
  description,
  size = 'md',
  variant = 'default',
}: CheckboxInputProps) => {
  const showErrorMessage = Boolean(isError && errorMessage);
  const feedbackMessage = showErrorMessage ? errorMessage : bottomLabel;

  // Size classes
  const sizeClasses = {
    sm: 'checkbox-sm',
    md: 'checkbox-md',
    lg: 'checkbox-lg',
  };

  // Variant classes
  const variantClasses = {
    default: '',
    primary: 'checkbox-primary',
    secondary: 'checkbox-secondary',
    success: 'checkbox-success',
    warning: 'checkbox-warning',
    info: 'checkbox-info',
    error: 'checkbox-error',
  };

  // Generate unique ID for accessibility using React's useId hook for SSR compatibility
  const generatedId = useId();
  const checkboxId = `checkbox-${name}-${generatedId}`;

  // Naked mode - only checkbox, no wrapper structure
  if (naked) {
    return (
      <div className='relative'>
        <input
          type='checkbox'
          id={checkboxId}
          name={name}
          value={value}
          checked={checked}
          onChange={onChange}
          onBlur={onBlur}
          onFocus={onFocus}
          disabled={disabled}
          readOnly={readOnly}
          className={cn(
            'checkbox',
            sizeClasses[size],
            variantClasses[variant],
            {
              'opacity-50 cursor-not-allowed': disabled,
              'cursor-pointer': !disabled && !readOnly,
            },
            className?.checkbox
          )}
          ref={(input) => {
            if (input) {
              input.indeterminate = indeterminate;
            }
          }}
        />

        {/* Loading State */}
        {isLoading && (
          <div className='absolute inset-0 flex items-center justify-center'>
            <span className='loading loading-spinner loading-xs opacity-50' />
          </div>
        )}
      </div>
    );
  }

  return (
    <div
      className={cn(
        'w-full flex flex-col gap-2 text-start',
        className?.wrapper
      )}
    >
      {/* Label with Tooltip Support */}
      {label && (
        <label
          htmlFor={checkboxId}
          className={cn(
            'w-full text-sm font-normal leading-5 flex items-start gap-2',
            {
              'text-error': isError,
              'text-gray-500': disabled,
            },
            className?.label
          )}
        >
          {/* Checkbox */}
          <div className='flex items-center gap-2'>
            {/* Start Adornment */}
            {startAdornment && (
              <span className={cn({ 'opacity-50': disabled })}>
                {startAdornment}
              </span>
            )}

            {/* Checkbox Input */}
            <div className='relative'>
              <input
                type='checkbox'
                id={checkboxId}
                name={name}
                value={value}
                checked={checked}
                onChange={onChange}
                onBlur={onBlur}
                onFocus={onFocus}
                disabled={disabled}
                readOnly={readOnly}
                className={cn(
                  'checkbox',
                  sizeClasses[size],
                  variantClasses[variant],
                  {
                    'opacity-50 cursor-not-allowed': disabled,
                    'cursor-pointer': !disabled && !readOnly,
                  },
                  className?.checkbox
                )}
                ref={(input) => {
                  if (input) {
                    input.indeterminate = indeterminate;
                  }
                }}
              />

              {/* Loading State */}
              {isLoading && (
                <div className='absolute inset-0 flex items-center justify-center'>
                  <span className='loading loading-spinner loading-xs opacity-50' />
                </div>
              )}
            </div>

            {/* Label Text */}
            <span
              className={cn('flex-1', {
                'line-through opacity-50': disabled,
              })}
            >
              {label}
              {required && (
                <>
                  {' '}
                  <span
                    className={cn('tooltip', {
                      'tooltip-error': isError,
                      'tooltip-base': !isError,
                    })}
                    data-tip={tooltip || 'required'}
                  >
                    <span
                      className={cn('text-xs font-bold', {
                        'text-error': isError,
                        'text-base-content/70': !isError,
                      })}
                    >
                      *
                    </span>
                  </span>
                </>
              )}
            </span>

            {/* End Adornment */}
            {endAdornment && (
              <span className={cn({ 'opacity-50': disabled })}>
                {endAdornment}
              </span>
            )}
          </div>
        </label>
      )}

      {/* Description */}
      {description && (
        <p
          className={cn('text-xs leading-4', {
            'text-gray-500': !isError,
            'text-error': isError,
            'opacity-50': disabled,
          })}
        >
          {description}
        </p>
      )}

      {/* Field Message */}
      <FieldMessage
        message={feedbackMessage}
        tone={showErrorMessage ? 'error' : 'info'}
        isVisible={showErrorMessage || Boolean(bottomLabel)}
      />
    </div>
  );
};

export default CheckboxInput;
