import { Button, Group, Select, Stack, Switch } from '@mantine/core';
import { useRef, useState } from 'react';
import { Controller } from 'react-hook-form';

import type { FormerAPICallType, FormerProps, FormerRef } from '../Former.types';

import { Former } from '../Former';
import { FormerRestHeadSpecAPI } from '../FormerRestHeadSpecAPI';
import { FormerModel } from '../FormerWrappers';
import { ApiFormData } from './apiFormData';

const StubAPI = (): FormerAPICallType => (mode, request, value) => {
  console.log('API Call', mode, request, value);
  if (mode === 'read') {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ a: 'Another Value', test: 'Loaded Value' });
      }, 1000);
    });
  }
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(value || {});
    }, 1000);
  });
};

export const FormTest = () => {
  const [request, setRequest] = useState<null | string>('insert');
  const [wrapped, setWrapped] = useState(false);
  const [disableHTML, setDisableHTML] = useState(false);
  const [apiOptions, setApiOptions] = useState({
    authToken: '',
    type: '',
    url: '',
  });
  const [layout, setLayout] = useState({
    buttonArea: "bottom",
    buttonAreaGroupProps: { justify: 'center' },
    title: 'Custom Former Title',
  } as FormerProps['layout']);

  const [open, setOpen] = useState(false);
  const [formData, setFormData] = useState({ a: 99, rid_usernote: 3047 });
  //console.log('formData render', formData);

  const ref = useRef<FormerRef>(null);
  return (
    <Stack h="100%" mih="400px" w="90%">
      <Group>
        <Select
          data={['insert', 'update', 'delete', 'select', 'view']}
          onChange={setRequest}
          value={request}
        />
        <Switch
          checked={wrapped}
          label="Wrapped in Drawer"
          onChange={(event) => setWrapped(event.currentTarget.checked)}
        />
        <Switch
          checked={disableHTML}
          label="Disable HTML Form"
          onChange={(event) => setDisableHTML(event.currentTarget.checked)}
        />
        <Select
        data={['top', 'bottom', 'none']}
  
          onChange={(value) => setLayout({ ...layout, buttonArea: value as 'bottom' | 'none' | 'top' })}
          value={layout?.buttonArea}
        />

        <Switch
          checked={apiOptions.type === 'api'}
          label="Use API"
          onChange={(event) =>
            setApiOptions({ ...apiOptions, type: event.currentTarget.checked ? 'api' : '' })
          }
        />
      </Group>
      <Button onClick={() => setOpen(true)}>Open Former Drawer</Button>
      <Group>
        <Button
          onClick={async () => {
            const valid = await ref.current?.validate();
            console.log('validate -> ', valid, ref.current);
          }}
        >
          Test Ref Values. See console
        </Button>
        <Button
          onClick={async () => {
            setTimeout(() => {
              ref.current?.close?.();
            }, 3000);
          }}
        >
          Test Show/Hide
        </Button>
      </Group>
      <FormerModel former={{ request: 'insert' }} onClose={() => setOpen(false)} opened={open}>
        <div>Test</div>
      </FormerModel>
      <Former
        disableHTMlForm={disableHTML}
        layout={layout}
        onAPICall={
          apiOptions.type === 'api'
            ? FormerRestHeadSpecAPI({
                authToken: apiOptions.authToken,
                url: apiOptions.url,
              })
            : StubAPI()
        }
        onChange={setFormData}
        onClose={() => setOpen(false)}
        opened={open}
        primeData={{ a: '66', test: 'primed' }}
        ref={ref}
        request={request as any}
        //wrapper={(children, getState) => <div>{children}</div>}
        //opened={true}
        uniqueKeyField="rid_usernote"
        useFormProps={{ criteriaMode: 'all', shouldUseNativeValidation: false }}
        values={formData}
        // wrapper={
        //   wrapped
        //     ? (children, opened, onClose, _onOpen, getState) => {
        //         const values = getState('values');
        //         return (
        //           <Drawer
        //             h={'100%'}
        //             onClose={() => onClose?.()}
        //             opened={opened ?? false}
        //             title={`Drawer Former - Current A Value: ${values?.a}`}
        //             w={'50%'}
        //           >
        //             <Paper h="100%" shadow="sm" w="100%" withBorder>
        //               {children}
        //             </Paper>
        //           </Drawer>
        //         );
        //       }
        //     : undefined
        // }
      >
        <Stack pb={'400px'}>
          <Stack>
            <Controller
              name="test"
              render={({ field }) => <input type="text" {...field} placeholder="A" />}
            />
            <Controller
              name="a"
              render={({ field }) => <input type="text" {...field} placeholder="B" />}
              rules={{ required: 'Field is required' }}
            />
            <Controller
              name="note"
              render={({ field }) => <input type="text" {...field} placeholder="note" />}
              rules={{ required: 'Field is required' }}
            />
          </Stack>
          {!disableHTML && (
            <Stack>
              <button type="submit">HTML Submit</button>
              <button type="reset">HTML Reset</button>
            </Stack>
          )}
        </Stack>
      </Former>
      {apiOptions.type === 'api' && (
        <ApiFormData
          onChange={(values) => {
            setApiOptions({ ...apiOptions, ...values });
          }}
          values={apiOptions}
        />
      )}
    </Stack>
  );
};
