/**
 * Copyright (c) 2020-present, Goldman Sachs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { observer } from 'mobx-react-lite';
import {
  DataGrid,
  type DataGridRowClickedEvent,
} from '@finos/legend-lego/data-grid';
import { Box } from '@mui/material';
import {
  GraphManagerState,
  type V1_LiteDataContract,
} from '@finos/legend-graph';
import type { LakehouseAdminStore } from '../../../stores/lakehouse/admin/LakehouseAdminStore.js';
import { useMemo, useRef, useState } from 'react';
import { useAuth } from 'react-oidc-context';
import {
  DataAccessRequestViewer,
  DataContractViewerState,
} from '@finos/legend-extension-dsl-data-product';
import {
  generateContractPagePath,
  generateLakehouseDataProductPath,
} from '../../../__lib__/LegendMarketplaceNavigation.js';

export const LakehouseAdminContractsDashboard = observer(
  (props: { adminStore: LakehouseAdminStore }) => {
    const { adminStore } = props;
    const auth = useAuth();
    // Keep the latest access token in a ref so the grid datasource always reads
    // the freshest token without being recreated on every token rotation
    // (which would otherwise cause the grid to reset and refetch).
    const tokenRef = useRef(auth.user?.access_token);
    tokenRef.current = auth.user?.access_token;

    const [selectedContract, setSelectedContract] = useState<
      V1_LiteDataContract | undefined
    >();

    const handleRowClicked = (
      event: DataGridRowClickedEvent<V1_LiteDataContract>,
    ) => {
      setSelectedContract(event.data);
    };

    const datasource = useMemo(
      () =>
        adminStore.createContractsServerSideDatasource(() => tokenRef.current),
      [adminStore],
    );

    return (
      <>
        <Box className="marketplace-lakehouse-admin__contracts__grid ag-theme-balham">
          <DataGrid
            rowModelType="serverSide"
            serverSideDatasource={datasource}
            suppressFieldDotNotation={true}
            suppressContextMenu={false}
            onRowClicked={handleRowClicked}
            onGridReady={(params) => {
              adminStore.setContractsGridApi(params.api);
            }}
            columnDefs={[
              {
                minWidth: 50,
                resizable: true,
                headerName: 'Contract Id',
                valueGetter: (p) => p.data?.guid,
                flex: 2,
              },
              {
                minWidth: 50,
                resizable: true,
                headerName: 'Contract Description',
                valueGetter: (p) => p.data?.description,
                flex: 2,
              },
              {
                minWidth: 10,
                resizable: true,
                headerName: 'Version',
                valueGetter: (p) => p.data?.version,
                flex: 1,
              },
              {
                minWidth: 50,
                resizable: true,
                headerName: 'State',
                valueGetter: (p) => p.data?.state,
                flex: 2,
              },
              {
                minWidth: 50,
                resizable: true,
                headerName: 'Members',
                valueGetter: (p) => p.data?.members.map((m) => m.user),
                flex: 1,
              },
              {
                minWidth: 50,
                resizable: true,
                headerName: 'Created By',
                valueGetter: (p) => p.data?.createdBy,
                flex: 1,
              },
            ]}
          />
        </Box>
        {selectedContract !== undefined && (
          <DataAccessRequestViewer
            open={true}
            onClose={() => setSelectedContract(undefined)}
            viewerState={
              new DataContractViewerState(
                selectedContract,
                (contractId: string, taskId: string) =>
                  adminStore.legendMarketplaceBaseStore.applicationStore.navigationService.navigator.generateAddress(
                    generateContractPagePath(contractId, taskId),
                  ),
                undefined,
                adminStore.legendMarketplaceBaseStore.applicationStore,
                adminStore.legendMarketplaceBaseStore.lakehouseContractServerClient,
                new GraphManagerState(
                  adminStore.legendMarketplaceBaseStore.applicationStore.pluginManager,
                  adminStore.legendMarketplaceBaseStore.applicationStore.logService,
                ),
                adminStore.legendMarketplaceBaseStore.userSearchService,
              )
            }
            onRefresh={() => adminStore.refresh()}
            getDataProductUrl={(dataProductId: string, deploymentId: number) =>
              adminStore.legendMarketplaceBaseStore.applicationStore.navigationService.navigator.generateAddress(
                generateLakehouseDataProductPath(dataProductId, deploymentId),
              )
            }
          />
        )}
      </>
    );
  },
);
