import * as stylex from '@stylexjs/stylex';

import type { ReactNode } from 'react';

import { useI18n } from '~/src/lib/i18n';
import { Layout } from '~/src/ui/layouts/layout';
import { Button } from '~/src/ui/primitives/button';
import { Text } from '~/src/ui/primitives/text';
import { FormFieldError } from './FormFieldError';
import { FormLabel } from './FormLabel';
import { FormFieldWidth } from './types';

interface FormFieldProps {
  children: ReactNode;
  label?: string;
  name: string;
  required?: boolean;
  description?: string;
  width?: FormFieldWidth;
  breakBefore?: boolean;
  onRemove?: () => void;
}

const MOBILE = '@media (max-width: 768px)';

const widthStyles = stylex.create({
  full: {
    gridColumn: 'span 12',
  },
  half: {
    gridColumn: {
      default: 'span 6',
      [MOBILE]: 'span 12',
    },
  },
  third: {
    gridColumn: {
      default: 'span 4',
      [MOBILE]: 'span 6',
    },
  },
  fourth: {
    gridColumn: {
      default: 'span 3',
      [MOBILE]: 'span 6',
    },
  },
  fullBreakBefore: {
    gridColumn: '1 / -1',
  },
  halfBreakBefore: {
    gridColumn: {
      default: '1 / span 6',
      [MOBILE]: '1 / -1',
    },
  },
  thirdBreakBefore: {
    gridColumn: {
      default: '1 / span 4',
      [MOBILE]: '1 / span 6',
    },
  },
  fourthBreakBefore: {
    gridColumn: {
      default: '1 / span 3',
      [MOBILE]: '1 / span 6',
    },
  },
});

export const FormField = ({
  label,
  name,
  children,
  description,
  width = 'full',
  breakBefore,
  onRemove,
}: FormFieldProps) => {
  const { t } = useI18n();

  return (
    <Layout
      column
      gap="3"
      style={widthStyles[breakBefore ? `${width}BreakBefore` : width]}
    >
      {(label || onRemove) && (
        <Layout gap="5" align="center" justify="space-between">
          {label && <FormLabel label={label} name={name} />}
          {onRemove && (
            <Button variant="text-danger" onClick={onRemove}>
              {t('app.actions.remove')}
            </Button>
          )}
        </Layout>
      )}
      {children}
      {description && <Text variant="subtext">{description}</Text>}
      <FormFieldError name={name} />
    </Layout>
  );
};
