import React from 'react';
import {
  DevicePluginClient,
  usePlugin,
  createState,
  useValue,
  Layout,
} from 'flipper-plugin';

// Read more: https://fbflipper.com/docs/tutorial/js-custom#creating-a-first-plugin
// API: https://fbflipper.com/docs/extending/flipper-plugin#pluginclient
export function devicePlugin(client: DevicePluginClient) {
  const data = createState<string[]>([]);

  client.device.onLogEntry((entry) => {
    data.update((draft) => {
      draft.push(entry.message);
    });
  });

  client.addMenuEntry({
    action: 'clear',
    handler: async () => {
      data.set([]);
    },
    accelerator: 'ctrl+l',
  });

  return {data};
}

// Read more: https://fbflipper.com/docs/tutorial/js-custom#building-a-user-interface-for-the-plugin
// API: https://fbflipper.com/docs/extending/flipper-plugin#react-hooks
export function Component() {
  const instance = usePlugin(devicePlugin);
  const data = useValue(instance.data);

  return (
    <Layout.ScrollContainer>
      {Object.entries(data).map(([id, d]) => (
        <pre key={id} data-testid={id}>
          {JSON.stringify(d)}
        </pre>
      ))}
    </Layout.ScrollContainer>
  );
}
