import { JSX } from '@redneckz/uni-jsx';
import { type ComponentType } from '../../model/ComponentType';
import { type LabelProps } from '../../model/HeadlineType';
import { Text } from '../../ui-kit/Text/Text';
import { type TextColor, type TextSize } from '../../ui-kit/Text/TextProps';
import { style } from '../../utils/style';

export interface CardCellProps extends ComponentType, LabelProps {
  labelSize?: TextSize;
  value?: string | string[];
  subText?: string;
  subColor?: TextColor;
  isPhone?: boolean;
}

export const CardCell = JSX<CardCellProps>(({ value, subText, children, isPhone, ...props }) => {
  const textItems = (Array.isArray(value) ? value : value?.split(',') ?? []).filter(Boolean);

  if ([textItems.length, children, subText].every((_) => !_)) {
    return null;
  }

  return renderCardCell({ textItems, subText, children, isPhone, ...props });
});

const renderCardCell = ({
  label,
  labelSize = 'text-m',
  textItems,
  subColor,
  subText,
  className,
  children,
  isPhone = false,
}: CardCellProps & { textItems: string[]; children: any }) => (
  <div className={style('flex gap-2xs flex-col h-full max-w-[300px]', className)}>
    {label ? (
      <Text color="text-secondary-text" font="font-light" size={labelSize}>
        {label}
      </Text>
    ) : null}
    {children || renderTextItems(textItems, isPhone)}
    {subText ? (
      <Text color={subColor} size="text-m">
        {subText}
      </Text>
    ) : null}
  </div>
);

const renderTextItems = (textItems: string[], isPhone: boolean) =>
  textItems.filter(Boolean).map((text, i) => (
    <Text key={String(i)} size="text-l">
      {isPhone ? <a href={`tel:${cleanPhoneNumber(text)}`}>{text.trim()}</a> : text.trim()}
    </Text>
  ));

const cleanPhoneNumber = (phone: string) => phone.replace(/\D/g, '');
