import { Component, createSignal, For } from 'solid-js';

import PersonIcon from '@suid/icons-material/Person';

import style from './Account.module.css';
import {
  Box,
  IconButton,
  InputLabel,
  NativeSelect,
  TextField,
} from '@suid/material';
import { useI18n } from '@solid-primitives/i18n';
import Dialog from '../dialog';
import dispatch from '../../workers/dispatcher-main';
import allGpxes from '../all-gpxes';
import gpx from '../gpx';
import { cloneDeep } from 'lodash';
import { getAccountById } from '../../db/account';

const Account: Component<{}> = (props) => {
  const [t] = useI18n();
  const [open, setOpen] = createSignal(false);
  const [settings, setSettings] = createSignal<any>();
  const [accounts, setAccounts] = createSignal<any>();
  const [account, setAccount] = createSignal<any>({});

  const handleClickOpen = async () => {
    setOpen(true);
    const newSettings: any = await dispatch({
      action: 'getSettings',
    });
    setSettings(newSettings || {});
    const newAccounts: any = await dispatch({
      action: 'getAccounts',
    });
    setAccounts([{ id: '--new--', name: t('newAccount') }, ...newAccounts]);
    setAccount(
      cloneDeep(getAccountById(accounts(), settings().currentAccountId))
    );

    console.log({
      caller: 'Account / handleClickOpen',
      settings: settings(),
      accounts: accounts(),
    });
  };

  const handleClose = (event: any, reason?: string) => {
    console.log({
      caller: 'Account / handleClose',
      event,
      reason,
    });
    if (reason === undefined) {
      setOpen(false);
    }
  };

  const changeAccountHandler = (event: any) => {
    const selectedAccountId = event.target.value;
    setAccount(cloneDeep(getAccountById(accounts(), selectedAccountId)));
    console.log({
      caller: 'Account / changeAccountHandler',
      event,
      selectedAccountName: selectedAccountId,
      account: account(),
    });
  };

  const changeHandlerFactory = (path: string) => (event: any) => {
    const value = event.target.value;
    const newAccount = cloneDeep(account());
    newAccount[path] = value;
    setAccount(newAccount);
    console.log({
      caller: 'Account / changeHandlerFactory / ' + path,
      event,
      value,
      account: account(),
    });
  };

  return (
    <>
      <div class={style.control}>
        <IconButton onClick={handleClickOpen}>
          <PersonIcon />
        </IconButton>
      </div>
      <Dialog
        open={open()}
        title={t('account')}
        closeHandler={handleClose}
        fullScreen={true}
      >
        <Box
          component='form'
          sx={{
            width: '100%',
            '& .MuiTextField-root': { m: 1, width: '100%' },
            paddingTop: '5px',
          }}
          noValidate
          autoComplete='off'
        >
          <InputLabel variant='normal' htmlFor='account-chooser'>
            {t('accountChooser')}
          </InputLabel>
          <NativeSelect
            inputProps={{
              name: 'account-chooser',
              id: 'account-chooser',
            }}
            onChange={changeAccountHandler}
          >
            <For each={accounts()}>
              {(account: any) => (
                <option
                  value={account.id}
                  selected={account.id === settings().currentAccountId}
                >
                  {account.name}
                </option>
              )}
            </For>
          </NativeSelect>

          <TextField
            label={t('accountName')}
            value={account().name || ''}
            onChange={changeHandlerFactory('name')}
          />

          <TextField
            label={t('localDb')}
            value={account().localDb || ''}
            onChange={changeHandlerFactory('localDb')}
          />

          <TextField
            label={t('remoteDbServer')}
            value={account().remoteDbServer || ''}
            onChange={changeHandlerFactory('remoteDbServer')}
          />

          <TextField
            label={t('remoteDbUser')}
            value={account().remoteDbUser || ''}
            onChange={changeHandlerFactory('remoteDbUser')}
          />

          <TextField
            label={t('remoteDbPassword')}
            value={account().remoteDbPassword || ''}
            onChange={changeHandlerFactory('remoteDbPassword')}
          />
        </Box>
      </Dialog>
    </>
  );
};

export default Account;
