import { ConfirmDialog } from '@/components/shared';
import { Button, FormItem, Input, FormContainer, Dialog } from '@/components/ui';
import NalertToast from '@/nafith/alertToast';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useParams } from 'react-router-dom';
import store from '../../store';
import { Field, Form, Formik } from 'formik';
import * as Yup from 'yup';
import { getValidationConstants } from '@/constants/validation.constant';
import { StatusIcon } from '@/nafith/shared';
import PropTypes from 'prop-types';
import { t } from 'i18next';

const PopupButton = ({
  actionFunction,
  actionName,
  actionIcon,
  actionColor,
  actionType,
  validateForm,
  data,
  setFieldTouched,
  textArea = false,
  dialogInformationMessage,
  storeData,
  navigatePath,
}) => {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { id } = useParams();
  const { t } = useTranslation();
  const navigate = useNavigate();
  const validationConstants = getValidationConstants(t);

  const onConfirmDialogOpen = () => {
    //mark all fields as touched
    Object.keys(data).forEach((key) => {
      setFieldTouched(key);
    });

    validateForm().then((errors) => {
      if (Object.keys(errors).length === 0) {
        setDialogOpen(true);
      }
    });
  };

  const onConfirmDialogClose = () => {
    setDialogOpen(false);
  };

  const handleConfirm = async (values) => {
    setIsSubmitting(true);
    setDialogOpen(false);
    const newFormData = storeData;
    const result = await actionFunction(id, data, newFormData, values);
    if (result.status === 'failed') {
      NalertToast(result.message, 'danger');
      setIsSubmitting(false);
    } else {
      NalertToast(t('THR_OPERATION_ACCOMPLISHED_SUCCESSFULLY'), 'success');
      navigate(navigatePath);
      setIsSubmitting(false);
    }
    return result.status;
  };

  return (
    <>
      <Button
        color={actionColor}
        variant="solid"
        loading={isSubmitting}
        size="sm"
        icon={actionIcon}
        type="button"
        onClick={onConfirmDialogOpen}
        className="order-2 mt-2 sm:mt-0"
        title={actionName}
      >
        {actionName}
      </Button>
      {textArea ? (
        <Dialog
          isOpen={dialogOpen}
          onClose={onConfirmDialogClose}
          onRequestClose={onConfirmDialogClose}
          style={{
            marginTop: 250,
          }}
          contentClassName="pb-0 px-0 w-full max-w-sm lg:max-w-lg"
        >
          <Formik
            initialValues={{ notes: '' }}
            validationSchema={Yup.object().shape({
              notes: Yup.string()
                .matches(
                  validationConstants?.textAreaValidationWithSymbols?.regex,
                  validationConstants?.textAreaValidationWithSymbols?.message,
                )
                .required(t('THIS_FIELD_IS_REQUIRED')),
            })}
            onSubmit={(values) => {
              handleConfirm(values);
            }}
          >
            {({ touched, errors }) => {
              return (
                <Form>
                  <FormContainer>
                    <div>
                      <div className="px-6 pb-6 pt-2 flex">
                        <div>
                          <StatusIcon status={actionType} />
                        </div>
                        <div className="ml-4 rtl:mr-4">
                          <h5 className="mb-2">{actionName}</h5>
                          <p>{t('ARE_YOU_SURE_TO_PERFORM_THIS_OPERATION')}</p>
                        </div>
                      </div>

                      <div className="px-20 pb-6 pt-2">
                        <FormItem
                          label={t('NOTES') + ' : '}
                          invalid={errors.notes && touched.notes}
                          errorMessage={errors.notes}
                        >
                          <Field
                            textArea
                            type="text"
                            autoComplete="off"
                            name="notes"
                            placeholder={t('NOTES')}
                            component={Input}
                            height="h-32"
                            width="w-96"
                          />
                        </FormItem>
                      </div>

                      <div className="ltr:text-right rtl:text-left px-6 py-3 bg-gray-100 dark:bg-gray-700 rounded-bl-lg rounded-br-lg">
                        <Button size="sm" className="ltr:mr-2 rtl:ml-2" onClick={onConfirmDialogClose} type="button">
                          {t('CANCEL')}
                        </Button>
                        <Button size="sm" variant="solid" color={actionColor} type="submit">
                          {t('CONFIRM')}
                        </Button>
                      </div>
                    </div>
                  </FormContainer>
                </Form>
              );
            }}
          </Formik>
        </Dialog>
      ) : (
        <ConfirmDialog
          isOpen={dialogOpen}
          onClose={onConfirmDialogClose}
          onRequestClose={onConfirmDialogClose}
          type={actionType}
          title={actionName}
          onCancel={onConfirmDialogClose}
          onConfirm={handleConfirm}
          confirmButtonColor={actionColor}
          cancelText={t('CANCEL')}
          confirmText={t('CONFIRM')}
        >
          <p>{dialogInformationMessage}</p>
        </ConfirmDialog>
      )}
    </>
  );
};

PopupButton.defaultProps = {
  actionColor: 'primary',
  actionType: 'warning',
  textArea: false,
  dialogInformationMessage: t('ARE_YOU_SURE_TO_PERFORM_THIS_OPERATION'),
  storeData: store?.getState()?.disputesDetailForm?.data?.formData,
  navigatePath:'/disputes/grid'
};

PopupButton.propTypes = {
  actionFunction: PropTypes.func.isRequired,
  actionName: PropTypes.string.isRequired,
  actionColor: PropTypes.string,
  actionType: PropTypes.string,
  validateForm: PropTypes.func.isRequired,
  data: PropTypes.object.isRequired,
  setFieldTouched: PropTypes.func.isRequired,
  textArea: PropTypes.bool,
  dialogInformationMessage: PropTypes.string,
};

export default PopupButton;
