import React, { useEffect } from 'react';
import { type ContentItem } from '../types';
import { FormInput } from './FormInput';
import { FormSelect } from './FormSelect';
import { FormCheckbox } from './FormCheckbox';
import { FormRadio } from './FormRadio';
import { FormTextarea } from './FormTextarea';
import { ActivityIndicator, Text, TouchableOpacity } from 'react-native';
import {
  getLayoutStyles,
  getTextStyles,
  getViewStyles,
} from '../utils/styleKeys';
import type { ContentViewItem } from '../store/contentModel';
import Resync from 'resync-javascript';
import Icon from '../ContentItem/icon';

interface FormRendererProps {
  element: ContentItem;
  contentItem: ContentViewItem;
  value: any;
  onChange: (value: any) => void;
  onBlur?: () => void;
  onSubmit?: () => void;
  error?: string;
  touched?: boolean;
  disabled?: boolean;
  loading?: boolean;
}

export const FormRenderer: React.FC<FormRendererProps> = ({
  element,
  contentItem,
  value,
  onChange,
  onBlur,
  onSubmit,
  error,
  touched,
  disabled,
  loading,
}) => {
  const type = element.elementType;

  useEffect(() => {
    if (element?.event && contentItem?.content?.id) {
      if (element.eventConfig?.action === 'view') {
        Resync.logEvent({
          eventId: element.event?.eventId || '',
          logId: element.eventConfig?.logId || '',
        });
        if (contentItem?.logAnalytics && element.eventConfig?.logId) {
          contentItem.logAnalytics(element.eventConfig?.logId, {
            itemId: element?.itemId,
            contentViewId: contentItem?.content?.id,
            ...element.eventConfig,
          });
        }
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  switch (type) {
    case 'input':
      return (
        <FormInput
          element={element}
          value={value || ''}
          onChange={onChange}
          onBlur={onBlur}
          error={error}
          touched={touched}
          disabled={disabled}
          contentItem={contentItem}
        />
      );

    case 'select':
      return (
        <FormSelect
          element={element}
          value={value || ''}
          onChange={onChange}
          onBlur={onBlur}
          error={error}
          touched={touched}
          disabled={disabled}
          contentItem={contentItem}
        />
      );

    case 'checkbox':
      return (
        <FormCheckbox
          element={element}
          value={value}
          onChange={onChange}
          onBlur={onBlur}
          error={error}
          touched={touched}
          disabled={disabled}
          contentItem={contentItem}
        />
      );

    case 'radio':
      return (
        <FormRadio
          element={element}
          value={value || ''}
          onChange={onChange}
          onBlur={onBlur}
          error={error}
          touched={touched}
          disabled={disabled}
          contentItem={contentItem}
        />
      );

    case 'textarea':
      return (
        <FormTextarea
          element={element}
          value={value || ''}
          onChange={onChange}
          onBlur={onBlur}
          error={error}
          touched={touched}
          disabled={disabled}
          contentItem={contentItem}
        />
      );
    case 'submit':
      const submit = () => {
        if (
          element.eventConfig?.action === 'click' &&
          contentItem?.content?.id
        ) {
          Resync.logEvent({
            eventId: element.event?.eventId || '',
            logId: element.eventConfig?.logId || '',
          });
          if (contentItem?.logAnalytics && element.eventConfig?.logId) {
            contentItem.logAnalytics(element.eventConfig?.logId, {
              itemId: element?.itemId,
              ...element.eventConfig,
              contentViewId: contentItem?.content?.id,
              metadata: value,
            });
          }
        }
        onSubmit?.();
      };
      return (
        <TouchableOpacity
          key={element.itemId}
          style={[
            getLayoutStyles(element?.data?.styles),
            getLayoutStyles(element.data?.customStyles || {}),
            getViewStyles(element?.data?.styles),
            getViewStyles(element.data?.customStyles || {}),
            {
              // @ts-ignore
              ...(element?.data?.properties?.iconPosition === 'left'
                ? {
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 8,
                  }
                : {}),
              // @ts-ignore
              ...(element?.data?.properties?.iconPosition === 'right'
                ? {
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 8,
                  }
                : {}),
            },
          ]}
          onPress={submit}
          disabled={disabled}
          {...element?.data?.customProps}
        >
          {loading ? (
            <ActivityIndicator size="small" />
          ) : (
            <>
              {/* @ts-ignore */}
              {element?.data?.icon?.name &&
                // @ts-ignore
                element?.data?.properties?.iconPosition === 'left' && (
                  <Icon
                    // @ts-ignore
                    {...(element?.data?.icon as {
                      name: string;
                      color: string;
                      size: number;
                      strokeWidth: number;
                    })}
                  />
                )}
              <Text
                style={[
                  getTextStyles(element?.data?.styles),
                  getTextStyles(element.data?.customStyles || {}),
                  {
                    // @ts-ignore
                    ...(!element?.data?.properties?.iconPosition
                      ? { width: '100%' }
                      : {}),
                  },
                ]}
                {...element?.data?.customProps}
              >
                {/* @ts-ignore */}
                {element?.data?.properties?.textContent}
              </Text>
              {/* @ts-ignore */}
              {element?.data?.icon?.name &&
                // @ts-ignore
                element?.data?.properties?.iconPosition === 'right' && (
                  <Icon
                    // @ts-ignore
                    {...(element?.data?.icon as {
                      name: string;
                      color: string;
                      size: number;
                      strokeWidth: number;
                    })}
                  />
                )}
            </>
          )}
        </TouchableOpacity>
      );
    default:
      console.warn(`Unsupported form element type: ${type}`);
      return null;
  }
};
