import { useCallback, useMemo, useState } from '@redneckz/uni-jsx/lib/hooks';
import { useForm } from '../../hooks/useForm/useForm';
import { ApplicationFormLayout } from '../../ui-kit/ApplicationFormLayout/ApplicationFormLayout';
import { SubmitButton } from '../../ui-kit/Button/SubmitButton';
import { getField } from '../../ui-kit/FormField/getField';
import { getFormValidator } from '../../ui-kit/FormField/getObjectValidator';
import { renderTitle } from '../../ui-kit/FormField/renderTitle';
import { titleColumnStyle } from '../../ui-kit/FormField/titleColumnStyle';
import { Link } from '../../ui-kit/Link/Link';
import { Paragraph } from '../../ui-kit/Paragraph/Paragraph';
import { type Option } from '../../ui-kit/Select/Option';
import { Text } from '../../ui-kit/Text/Text';
import { UniBlock } from '../../UniBlock/UniBlock';
import { type UniBlockProps } from '../../UniBlock/UniBlockProps';
import { type FieldDef } from '../ApplicationForm/ApplicationFormContent';
import { type ReferalFormContent } from './ReferalFormContent';
import { inputs } from './referalFormData';
import { ResultLink } from './ResultLink';

export interface FormState {
  email?: string;
  dadataPartyInnSelect?: Option;
}

export interface ReferalFormProps extends ReferalFormContent, UniBlockProps {}

const COLUMNS = 2;

export const ReferalForm = UniBlock<ReferalFormProps>(
  ({ title, description, link = '', button, copyIcon, ...rest }) => {
    const [isShowResultLink, setIsShowResultLink] = useState(false);
    const [referalLink, setReferalLink] = useState('');

    const formValidator = useMemo(() => getFormValidator(inputs), [inputs]);

    const handleSubmit = useCallback(async (formData: FormState) => {
      setReferalLink(
        `${link}?utm_source=${formData.dadataPartyInnSelect?.text}&utm_mail=${formData.email}`,
      );
      setIsShowResultLink(true);
    }, []);

    const [, { field, onSubmit }] = useForm(
      {},
      {
        resetOnSubmit: true,
        formValidator,
        onSubmit: handleSubmit,
      },
    );

    return (
      <ApplicationFormLayout
        className="container space-y-m col-span-12"
        title={getTitle(title, isShowResultLink)}
        {...rest}
      >
        {isShowResultLink ? (
          <ResultLink link={referalLink} copyIcon={copyIcon} />
        ) : (
          <form onSubmit={onSubmit}>
            <div className="grid @xl:grid-cols-2 gap-x-m">
              {renderTitle(description, titleColumnStyle(COLUMNS))}
              {inputs.map(getField<FieldDef>(field))}
            </div>
            <Paragraph size="text-l" font="font-light" color="text-secondary-text">
              <Text>Нажимая кнопку, вы подтверждаете согласие с </Text>
              <Link href="/privacy-policy" target="_blank" ariaLabel="условия передачи данных">
                условиями передачи данных
              </Link>
            </Paragraph>
            <SubmitButton className="w-full @xl:w-auto mt-xs">
              {button?.text ?? 'Получить ссылку'}
            </SubmitButton>
          </form>
        )}
      </ApplicationFormLayout>
    );
  },
);

const getTitle = (title = '', isShowResultLink = false) =>
  isShowResultLink ? 'Ваша личная ссылка' : title;
