import {
  createTextField,
  jsonServerProvider,
  ListTable,
  Resource,
  Tushan,
  fetchJSON
} from 'tushan';
import { authProvider } from './auth';
import { userFields, payFields, kbFields, ModelFields } from './fields';

const authStorageKey = 'tushan:auth';

const httpClient: typeof fetchJSON = (url, options = {}) => {
  try {
    if (!options.headers) {
      options.headers = new Headers({ Accept: 'application/json' });
    }
    const { token } = JSON.parse(window.localStorage.getItem(authStorageKey) ?? '{}');
    (options.headers as Headers).set('Authorization', `Bearer ${token}`);

    return fetchJSON(url, options);
  } catch (err) {
    return Promise.reject();
  }
};

const dataProvider = jsonServerProvider(import.meta.env.VITE_PUBLIC_SERVER_URL, httpClient);

function App() {
  return (
    <Tushan
      basename="/"
      header={'FastGpt-Admin'}
      dataProvider={dataProvider}
      authProvider={authProvider}
    >
      <Resource
        name="users"
        label="用户信息"
        list={
          <ListTable
            filter={[
              createTextField('username', {
                label: 'username'
              })
            ]}
            fields={userFields}
            action={{ detail: true, edit: true }}
          />
        }
      />

      <Resource
        name="pays"
        label="支付记录"
        list={
          <ListTable
            filter={[
              createTextField('userId', {
                label: 'userId'
              })
            ]}
            fields={payFields}
            action={{ detail: true }}
          />
        }
      />
      <Resource
        name="kbs"
        label="知识库"
        list={
          <ListTable
            filter={[
              createTextField('tag', {
                label: 'tag'
              })
            ]}
            fields={kbFields}
            action={{ detail: true }}
          />
        }
      />
      <Resource
        name="models"
        label="应用"
        list={<ListTable fields={ModelFields} action={{ detail: true }} />}
      />
    </Tushan>
  );
}

export default App;
