/**
 * CheckboxCell Component
 *
 * Checkbox cell for boolean values.
 * Memoized to prevent unnecessary re-renders when parent table updates.
 */

import { useState, useEffect, useCallback, memo } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { cn } from '@/lib/utils';
import type { Field, SelectOption } from '../../../../types';
import type { ValidationError } from '../../store/types';

interface CheckboxCellProps {
  value: unknown;
  field: Field<string>;
  options?: SelectOption[];
  rowIndex: number;
  isValidating: boolean;
  errors: ValidationError[];
  onChange: (value: unknown) => void;
  onBlur: (value: unknown) => void;
  onFetchOptions?: () => void;
  booleanMatches?: Record<string, boolean>;
}

const CheckboxCellComponent = ({
  field,
  value,
  isValidating,
  errors,
  onChange,
  onBlur,
  booleanMatches = {},
}: CheckboxCellProps) => {
  const [checked, setChecked] = useState(false);

  // Initialize checkbox state
  useEffect(() => {
    if (value === undefined || value === null) {
      setChecked(false);
      return;
    }

    if (typeof value === 'boolean') {
      setChecked(value);
      return;
    }

    // Handle string values using booleanMatches
    if (typeof value === 'string') {
      // First try the field's booleanMatches
      const fieldBooleanMatches =
        field.fieldType.type === 'checkbox' ? field.fieldType.booleanMatches || {} : {};

      // Merge with the provided booleanMatches, with the provided ones taking precedence
      const allMatches = { ...fieldBooleanMatches, ...booleanMatches };

      // Try to find the value in the matches
      const matchEntry = Object.entries(allMatches).find(
        ([k]) => k.toLowerCase() === value.toLowerCase()
      );

      if (matchEntry) {
        setChecked(matchEntry[1]);
        return;
      }

      // If no match found, use common true/false strings
      const trueStrings = ['yes', 'true', '1', 'y'];
      const falseStrings = ['no', 'false', '0', 'n'];

      if (trueStrings.includes(value.toLowerCase())) {
        setChecked(true);
        return;
      }

      if (falseStrings.includes(value.toLowerCase())) {
        setChecked(false);
        return;
      }
    }

    // For any other values, try to convert to boolean
    setChecked(!!value);
  }, [value, field.fieldType, booleanMatches]);

  // Handle checkbox change
  const handleChange = useCallback(
    (checked: boolean) => {
      setChecked(checked);
      onChange(checked);
      onBlur(checked);
    },
    [onChange, onBlur]
  );

  const hasError = errors.length > 0;

  return (
    <div
      className={cn(
        'flex items-center justify-center h-8 w-full rounded-md border',
        hasError ? 'bg-red-50 border-destructive' : 'border-input',
        isValidating && 'opacity-50'
      )}
    >
      <Checkbox
        checked={checked}
        onCheckedChange={handleChange}
        disabled={isValidating}
        className={cn(hasError ? 'border-destructive' : '')}
      />
    </div>
  );
};

// Memoize to prevent re-renders when parent table state changes
export const CheckboxCell = memo(CheckboxCellComponent);
