import { Checkbox as BaseCheckbox } from '@base-ui/react/checkbox';
import * as stylex from '@stylexjs/stylex';
import { Controller, useFormContext } from 'react-hook-form';

import type { FormCustomField } from './types';

import { sanitizeRichText } from '~/src/lib/utils/sanitizeRichText';
import {
  colors,
  fontSizes,
  radius,
  spacing,
  textColors,
} from '~/src/ui/tokens/tokens.stylex';
import { FormField } from './FormField';

const styles = stylex.create({
  row: {
    display: 'flex',
    alignItems: 'flex-start',
    gap: spacing[4],
  },
  box: {
    boxSizing: 'border-box',
    flexShrink: 0,
    margin: 0,
    padding: 0,
    width: '2rem',
    height: '2rem',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    borderStyle: 'solid',
    borderWidth: 1,
    borderColor: {
      default: colors.gray400,
      ':hover': colors.gray600,
    },
    borderRadius: radius[2],
    backgroundColor: colors.gray100,
    color: textColors.primary,
    cursor: 'pointer',
  },
  boxInvalid: {
    borderColor: colors.red,
  },
  indicator: {
    display: 'flex',
    width: '1.2rem',
    height: '1.2rem',
  },
  label: {
    fontSize: fontSizes.bodySmall,
    lineHeight: 1.4,
    color: textColors.primary,
    cursor: 'pointer',
  },
});

const CheckIcon = () => (
  <svg viewBox="0 0 14 14" fill="none" width="100%" height="100%">
    <path
      d="M11.5 4L5.75 10L2.5 6.7"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
  </svg>
);

export const FormCheckboxControl = (props: FormCustomField) => {
  const { control } = useFormContext();

  const { name, label, required } = props;

  return (
    <Controller
      control={control}
      name={name}
      rules={{ required }}
      render={({ field: { onChange, onBlur, value, ref }, fieldState }) => (
        <div {...stylex.props(styles.row)}>
          <BaseCheckbox.Root
            id={name}
            name={name}
            inputRef={ref}
            checked={Boolean(value)}
            onCheckedChange={(checked) => onChange(checked)}
            onBlur={onBlur}
            required={required}
            {...stylex.props(
              styles.box,
              fieldState.invalid && styles.boxInvalid
            )}
          >
            <BaseCheckbox.Indicator {...stylex.props(styles.indicator)}>
              <CheckIcon />
            </BaseCheckbox.Indicator>
          </BaseCheckbox.Root>
          {label && (
            <label htmlFor={name} {...stylex.props(styles.label)}>
              <span
                dangerouslySetInnerHTML={{ __html: sanitizeRichText(label) }}
              />
            </label>
          )}
        </div>
      )}
    />
  );
};

export const FormCheckbox = (props: FormCustomField) => {
  // The consent copy lives in `label` and is rendered next to the checkbox
  // (as HTML), so suppress FormField's own label to avoid duplicating it.
  return (
    <FormField {...props} label={undefined}>
      <FormCheckboxControl {...props} />
    </FormField>
  );
};
