/**
 * @license
 * Copyright (c) 2014, 2024, Oracle and/or its affiliates.
 * Licensed under The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */

import { h } from "preact";
import ActivityContainer from "./Activity/ActivityContainer";
import ParentContainer2 from "./ParentContainer2";
import { RESTDataProvider } from "ojs/ojrestdataprovider";
import { useState, useMemo, useRef } from "preact/hooks";

type Item = {
  id: number;
  name: string;
  short_desc?: string;
  price?: number;
  quantity?: number;
  quantity_shipped?: number;
  quantity_instock?: number;
  activity_id?: number;
  image?: string;
};

let keyAttributes: string = 'id';
// REST endpoint that returns Activity data
const restServerURLActivities: string =
  'https://apex.oracle.com/pls/apex/oraclejet/lp/activities/';

type Activity = {
  id: number;
  name: string;
  short_desc: string;
};


const ParentContainer1 = () => {

  const [fetchStatus, setFetchStatus] = useState(true);
  const fetchError = useRef<string>();

  const fetchErrorHandler = (errorDetail: RESTDataProvider.FetchErrorDetail<number, Activity> |
    RESTDataProvider.FetchResponseErrorDetail<number, Activity>) => {
    setFetchStatus(false);
    if (errorDetail.hasOwnProperty('response')) {
      fetchError.current = `${(errorDetail as RESTDataProvider.FetchResponseErrorDetail<number, Activity>).response.status}`;
    }
    else {
      fetchError.current = (errorDetail as RESTDataProvider.FetchErrorDetail<number, Activity>).error.message;
    }
  }

  const activityDataProvider = useMemo(() => new RESTDataProvider<Activity["id"], Activity>({
    keyAttributes: keyAttributes,
    url: restServerURLActivities,
    error: fetchErrorHandler,
    transforms: {
      fetchFirst: {
        request: async (options) => {
          const url = new URL(options.url);
          const { size, offset } = options.fetchParameters;
          url.searchParams.set("limit", String(size));
          url.searchParams.set("offset", String(offset));
          return new Request(url.href);
        },
        response: async ({ body }) => {
          const { items, totalSize, hasMore } = body;
          return { data: items, totalSize, hasMore };
        },
      },
    },
  }), [])

  const [selectedActivity, setSelectedActivity] = useState<Item | null>(null);

  const showActivityItems = () => {
    return selectedActivity != null ? true : false;
  };

  const activityChangedHandler = (value: Item) => {
    setSelectedActivity(value);
  };

  return (
    <div>
      {fetchStatus ? (
        <div id="parentContainer1" class="oj-flex oj-flex-init">
          <ActivityContainer data={activityDataProvider} onActivityChanged={activityChangedHandler} />
          {showActivityItems() && (<ParentContainer2 activity={selectedActivity} />)}
          {!showActivityItems() && (<h4 class="oj-typography-subheading-sm">Select activity to view items</h4>)}
        </div>) :
        (<p>Sorry that we couldn't get your product information right now. Please contact your system administrator.</p>
        )}
    </div>
  );
};

export default ParentContainer1;