import React from 'react';

import { KintoneRestAPIClient } from '@kintone/rest-api-client';
import { Properties as KintoneFormFieldProperties } from '@kintone/rest-api-client/lib/src/client/types';
import moize from 'moize';
import invariant from 'tiny-invariant';
import { PLUGIN_ID } from '../common/global';
import KintonePluginAlert from '../common/ui/KintonePluginAlert';
import KintonePluginButton from '../common/ui/KintonePluginButton';
import KintonePluginDesc from '../common/ui/KintonePluginDesc';
import KintonePluginLabel from '../common/ui/KintonePluginLabel';
import KintonePluginRequire from '../common/ui/KintonePluginRequire';
import KintonePluginRow from '../common/ui/KintonePluginRow';
import KintonePluginSelect, { KintonePluginSelectOptionData } from '../common/ui/KintonePluginSelect';
import KintonePluginTitle from '../common/ui/KintonePluginTitle';

import styles from './Settings.module.css';

const cachedFormFieldsProperties = moize.promise(async (appId: number): Promise<KintoneFormFieldProperties> => {
  const client = new KintoneRestAPIClient();
  const { properties } = await client.app.getFormFields({ app: appId, lang: 'en', preview: false });
  return properties;
});

const Settings: React.FC = () => {
  const config = kintone.plugin.app.getConfig(PLUGIN_ID);
  const appId = kintone.app.getId();
  invariant(appId, 'The app ID is not available. Please ensure you are on a Kintone app page.');
  const properties = React.use(cachedFormFieldsProperties(appId));
  const fileFields = Object.values(properties).filter((property) => property.type === 'FILE');
  const options: KintonePluginSelectOptionData[] = [
    { key: '-', value: '', label: 'Select a File field', disabled: true }, // Default option
    ...fileFields.map((property) => ({
      key: property.code,
      value: property.code,
      label: property.label,
    })),
  ];

  const [template, setTemplate] = React.useState<string>(
    () => options.find((option) => option.value === (config.template ?? ''))?.value ?? '',
  );

  const handleOnSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    kintone.plugin.app.setConfig({ template }, () => {
      alert('The plug-in settings have been saved. Please update the app!');
      window.location.href = `../../flow?app=${appId}`;
    });
  };

  const handleOnChangeTemplate = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setTemplate(e.target.value);
  };

  const handleOnClickCancel = () => {
    window.location.href = `../../${appId}/plugin/`;
  };

  return (
    <section className="settings">
      <KintonePluginLabel>Settings for the Kintone Word output plugin</KintonePluginLabel>
      <form onSubmit={handleOnSubmit}>
        <KintonePluginRow>
          <KintonePluginTitle>
            Template<KintonePluginRequire>*</KintonePluginRequire>
          </KintonePluginTitle>
          <KintonePluginDesc>Select a file field that contains the WORD template file.</KintonePluginDesc>
          {fileFields.length === 0 ? (
            <KintonePluginAlert>
              No file fields found in the app. Please add a file field to use this plugin.
            </KintonePluginAlert>
          ) : (
            <KintonePluginSelect defaultValue={template} onChange={handleOnChangeTemplate} options={options} />
          )}
        </KintonePluginRow>
        <KintonePluginRow className={styles.buttons}>
          <KintonePluginButton variant="dialog-cancel" type="button" onClick={handleOnClickCancel}>
            Cancel
          </KintonePluginButton>
          <KintonePluginButton variant="dialog-ok" type="submit">
            Save
          </KintonePluginButton>
        </KintonePluginRow>
      </form>
    </section>
  );
};
export default Settings;
