import * as React from "react";
import {
  Admin,
  Resource,
  List,
  Datagrid,
  TextField,
  NumberField,
  ReferenceField,
  Edit,
  SimpleForm,
  TextInput,
  NumberInput,
  EditProps,
  ShowProps,
  ListProps,
  Show,
  SimpleShowLayout,
  DataProvider,
} from "react-admin";
import { client } from "@logilab/cwclientlibjs";
import { createDataProvider } from "ra-cubicweb/dist";

import { schema } from "./schema";

export const MuseumShow = (props: ShowProps) => (
  <Show {...props}>
    <SimpleShowLayout>
      <TextField source="postal_address" />
      <NumberField source="longitude" />
      <NumberField source="latitude" />
      <TextField source="name" />
      <TextField source="id" />
      <ReferenceField label="City" link="show" reference="City" source="is_in">
        <TextField source="name" />
      </ReferenceField>
    </SimpleShowLayout>
  </Show>
);

const MuseumEdit = (props: EditProps) => (
  <Edit {...props}>
    <SimpleForm>
      <NumberInput source="id" />
      <TextInput source="name" />
      <NumberInput source="latitude" />
      <NumberInput source="longitude" />
      <TextInput source="postal_address" />
    </SimpleForm>
  </Edit>
);

const MuseumList = (props: ListProps) => (
  <List {...props}>
    <Datagrid rowClick="show">
      <NumberField source="id" />
      <TextField source="name" />
      <NumberField source="latitude" />
      <NumberField source="longitude" />
      <TextField source="postal_address" />
    </Datagrid>
  </List>
);

export const CityList = (props: ListProps) => (
  <List {...props}>
    <Datagrid rowClick="show">
      <NumberField source="zip_code" />
      <TextField source="name" />
      <TextField source="id" />
    </Datagrid>
  </List>
);

export const CityShow = (props: ShowProps) => (
  <Show {...props}>
    <SimpleShowLayout>
      <NumberField source="zip_code" />
      <TextField source="name" />
      <TextField source="id" />
    </SimpleShowLayout>
  </Show>
);

const httpClient = new client.CwSimpleHttpClient("http://localhost:8080", true);
const rqlClient = new client.CwRqlClient(httpClient);

const dataProvider = createDataProvider(rqlClient, schema);
dataProvider.getList("toto", {
  pagination: { page: 1, perPage: 10 },
  sort: { field: "id", order: "ASC" },
  filter: null,
});

const App = (): JSX.Element => (
  <Admin dataProvider={dataProvider as DataProvider}>
    {
      // authProvider={authProvider}
      // use cwclientlibjs to get list of CWETypes
      // and add one <Resource  per type
    }
    <Resource
      name="Museum"
      list={MuseumList}
      show={MuseumShow}
      edit={MuseumEdit}
    />
    <Resource name="City" list={CityList} show={CityShow} />
  </Admin>
);

export default App;