import { useI18n } from '@solid-primitives/i18n';
import {
  Dialog,
  Box,
  TextField,
  Stack,
  Button,
  IconButton,
} from '@suid/material';
import { cloneDeep } from 'lodash';
import { Component, createSignal } from 'solid-js';
import { emptyWpt } from '../../db/wpt';
import { peekCachedSignal } from '../../workers/cached-signals';
import dispatch from '../../workers/dispatcher-main';
import EditIcon from '@suid/icons-material/Edit';

enum Mode {
  CLOSED,
  EDIT,
}

interface Props {
  wptId?: string;
}

const WptEditor: Component<Props> = ({ wptId }) => {
  const [mode, setMode] = createSignal<Mode>(Mode.CLOSED);
  const [editedWpt, setEditedWpt] = createSignal<Wpt>();

  const [t, { add, locale, dict }] = useI18n();

  const wpt =
    wptId !== undefined
      ? peekCachedSignal({ id: wptId, method: 'getWpt' })
      : () => emptyWpt;

  const edit = () => {
    setMode(Mode.EDIT);
    setEditedWpt(cloneDeep(wpt()));
  };

  const closeHandler = () => {
    setMode(Mode.CLOSED);
  };

  const saveHandler = () => {
    console.log({
      caller: 'Wpt / saveHandler',
      wptId,
      editedWpt: editedWpt(),
    });
    dispatch({ action: 'putWpt', params: { id: wptId, wpt: editedWpt() } });
    setMode(Mode.CLOSED);
  };

  const getTitle = () => {
    if (wpt()?.name) {
      return `${wpt()?.name} (${t('wpt')})`;
    }
    return t('wpt');
  };

  return (
    <>
      <IconButton onClick={edit}>
        <EditIcon />
      </IconButton>
      <Dialog
        open={mode() === Mode.EDIT}
        title={getTitle()}
        closeHandler={closeHandler}
      >
        <Box sx={{ flexGrow: 1, padding: '10px' }}>
          <div>
            <TextField
              required
              label={t('name')}
              defaultValue={wpt()?.name}
              onChange={(event: any, value: string) => {
                setEditedWpt({ ...editedWpt(), name: value });
              }}
            />
            <TextField
              label={t('sym')}
              defaultValue={wpt()?.sym}
              onChange={(event: any, value: string) => {
                setEditedWpt({ ...editedWpt(), sym: value });
              }}
            />
            <TextField
              label={t('minZoom')}
              defaultValue={wpt()?.extensions?.['dyo:minZoom']?.toString()}
              onChange={(event: any, value: string) => {
                const extensions = {
                  ...editedWpt()?.extensions,
                  'dyo:minZoom': parseFloat(value),
                };
                setEditedWpt({ ...editedWpt(), extensions });
              }}
            />
            <Stack spacing={2} direction='row' sx={{ marginTop: '20px' }}>
              <Button
                variant='outlined'
                color='secondary'
                onClick={closeHandler}
              >
                {t('cancel')}
              </Button>
              <Button variant='contained' color='success' onClick={saveHandler}>
                {t('save')}
              </Button>
            </Stack>
          </div>
        </Box>
      </Dialog>
    </>
  );
};

export default WptEditor;
