import { Button, Checkbox, Divider, Group, Stack, TagsInput, TextInput } from '@mantine/core';
import { useLocalStorage } from '@mantine/hooks';
import { useRef, useState } from 'react';

import type { GridlerColumns } from '../components/Column';

import { GlidlerAPIAdaptorForGoLangv2 } from '../components/adaptors';
import { type GridlerRef } from '../components/GridlerStore';
import { Gridler } from '../Gridler';

export const GridlerGoAPIExampleEventlog = () => {
  const [apiUrl, setApiUrl] = useLocalStorage({
    defaultValue: 'http://localhost:8080/api',
    key: 'apiurl',
  });
  const ref = useRef<GridlerRef>(null);
  const [apiKey, setApiKey] = useLocalStorage({ defaultValue: '', key: 'apikey' });
  const [selectRow, setSelectRow] = useState<string | undefined>('');
  const [values, setValues] = useState<Array<Record<string, any>>>([]);
  const [sections, setSections] = useState<Record<string, unknown> | undefined>(undefined);
  const columns: GridlerColumns = [
    {
      Cell: (row) => {
        const process = `${
          row?.cql2?.length > 0
            ? '🔖'
            : row?.cql1?.length > 0
              ? '📕'
              : row?.status === 1
                ? '💡'
                : row?.status === 2
                  ? '🔒'
                  : '⚙️'
        } ${String(row?.id_process ?? '0')}`;

        return {
          data: process,
          displayData: process,
          status: row?.status,
        } as any;
      },
      id: 'id_process',
      title: 'RID',
      width: 100,
    },

    {
      id: 'process',
      title: 'Process',
      tooltip: (buffer) => {
        return `Process: ${buffer?.process}\nType: ${buffer?.processtype}\nStatus: ${buffer?.status}`;
      },
      width: 200,
    },
    {
      id: 'processtype',
      title: 'Type',
    },

    {
      disableSort: true,
      id: 'status',
      title: 'Status',
      width: 100,
    },
  ];

  return (
    <Stack h="80vh" w="50vw">
      <h2>Demo Using Go API Adaptor</h2>
      <TextInput label="API Url" onChange={(e) => setApiUrl(e.target.value)} value={apiUrl} />
      <TextInput label="API Key" onChange={(e) => setApiKey(e.target.value)} value={apiKey} />
      <Divider />
      <Checkbox
        checked={!!sections}
        label="Show Side Sections"
        onChange={(e) => {
          // eslint-disable-next-line @typescript-eslint/no-unused-expressions
          e.target.checked
            ? setSections({
                bottom: <div style={{ backgroundColor: 'teal', height: '25px' }}>bottom</div>,
                left: <div style={{ backgroundColor: 'orange', width: '20px' }}>L</div>,
                right: <div style={{ backgroundColor: 'green', width: '20px' }}>R</div>,
                top: <div style={{ backgroundColor: 'purple', height: '20px' }}>top</div>,
              })
            : setSections(undefined);
        }}
      />
      <Divider />
      <Gridler
        columns={columns}
        height="100%"
        // getMenuItems={(id, _state, row, col, defaultItems) => {
        //   console.log('GridlerGoAPIExampleEventlog getMenuItems root', id, row, col, defaultItems);
        //   return [
        //     ...(defaultItems ?? []),
        //     // {
        //     //   id: 'test',
        //     //   label: `Test -${id}`,
        //     //   onClick: () => {
        //     //     console.log('Test clicked', row, col);
        //     //   },
        //     // },
        //   ];
        // }}
        keyField="id_process"
        onChange={(v) => {
          //console.log('GridlerGoAPIExampleEventlog onChange', v);
          setValues(v);
        }}
        ref={ref}
        scrollToRowKey={selectRow ? parseInt(selectRow, 10) : undefined}
        sections={{ ...sections, rightElementDisabled: false }}
        selectFirstRowOnMount={true}
        selectMode="row"
        title="Go API Example"
        uniqueid="gridtest"
        values={values}
      >
        <GlidlerAPIAdaptorForGoLangv2
          authtoken={apiKey}
          //options={[{ type: 'fieldfilter', name: 'process', value: 'test' }]}
          url={`${apiUrl}/public/process`}
        />
        <Gridler.FormAdaptor
          descriptionField={'process'}
          onRequestForm={(request, data) => {
            console.log('Form requested', request, data);
          }}
        />
      </Gridler>
      <Divider />
      <Group>
        <TextInput
          onChange={(e) => setSelectRow(e.target.value)}
          placeholder="row"
          value={selectRow}
          w="90px"
        />
        <TagsInput
          data={[]}
          onChange={(str) => setValues(str.map((v) => ({ id_process: String(v) })))}
          placeholder="Values"
          value={values.map((v) => String(v?.id_process))}
        />
        ;
      </Group>
      <Group>
        <Button
          onClick={() => {
            ref.current?.refresh();
          }}
        >
          Refresh
        </Button>
        <Button
          onClick={() => {
            ref.current?.selectRow(20523);
          }}
        >
          Select 20523
        </Button>
        <Button
          onClick={() => {
            ref.current?.selectRow(4);
          }}
        >
          Select 4
        </Button>
        <Button
          onClick={() => {
            ref.current?.reloadRow(20523);
          }}
        >
          Reload 20523
        </Button>
        <Button
          onClick={() => {
            ref.current?.scrollToRow(16272);
          }}
        >
          Goto 2050
        </Button>
      </Group>
    </Stack>
  );
};
