import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import _ from 'lodash';
import { App, useApps } from 'src/services/apps';
import { Modal } from 'src/components';
import { Input } from 'src/components/Form';
import { AppInstallModalProps } from './types';
import { initialAppForm, initialCode } from './consts';

export const AppInstallModal = ({ open, onClose, appSlug }: AppInstallModalProps) => {
  const [appName, setAppName] = useState('');
  const { app, appLoading, installApp, loadApp, clearSelectedApp } = useApps();

  const { control, reset, handleSubmit } = useForm<App>({
    defaultValues: initialAppForm,
  });

  useEffect(() => {
    if (appSlug) {
      loadApp(appSlug);
    }

    return () => {
      reset(initialAppForm);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [appSlug, open]);

  useEffect(() => {
    if (!_.isEmpty(app)) {
      setAppName(app.name);
      reset({ url: app.url, configuration: initialCode, slug: appSlug ?? '' });
    }

    return () => {
      reset({ url: initialAppForm.url, configuration: initialCode, slug: appSlug ?? '' });
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [app, reset, open]);

  const handleClose = () => {
    clearSelectedApp();
    reset();
    onClose();
  };

  const handleSave = async () => {
    try {
      await handleSubmit((data) => installApp(data))();
    } catch (e: any) {
      // Continue
    }
    handleClose();
  };

  const handleKeyPress = (e: any) => {
    if (e.key === 'Enter' || e.key === 'NumpadEnter') {
      handleSave();
    }
  };

  return (
    <Modal onClose={handleClose} open={open} onSave={handleSave} isLoading={appLoading} useCancelButton>
      <div className="bg-white px-4">
        <div className="space-y-10 divide-y divide-gray-200">
          <div>
            <div>
              <h3 className="text-lg leading-6 font-medium text-gray-900">Install app {appName}</h3>
            </div>

            <div className="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
              <div className="sm:col-span-3">
                <Input control={control} name="url" label="URL" onKeyPress={handleKeyPress} required={false} />
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};
