import { Button, Rows, Text, Box, Masonry, MasonryItem, ImageCard, Accordion, AccordionItem } from "@canva/app-ui-kit";
import { requestOpenExternalUrl } from "@canva/platform";
import { FormattedMessage, useIntl } from "react-intl";
import * as styles from "styles/components.css";
import { useAddElement } from "utils/use_add_element";
import React, { useState, useEffect } from "react"
import { getCurrentPageContext, addElementAtPoint } from '@canva/design';
import { ImageMimeType, upload } from "@canva/asset"

const baseURL = `https://192.168.100.3:81/`
const baseApiURL = `${baseURL}api/canva/v1/`;

export const DOCS_URL = "https://www.canva.dev/docs/apps/";

export const App = () => {
  const addElement = useAddElement();
  const [loading, setLoading] = useState(false);

  const [assets, setAssets] = useState([]);
  const [draft, setDraft] = useState(null);

  const fontWeights = {
    '100': "thin",
    '200': "extralight",
    '300': "light",
    '400': "normal",
    '500': "medium",
    '600': "semibold",
    '700': "bold",
    '800': "ultrabold",
    '900': "heavy"
  };

  const onClick = () => {
    addElement({
      type: "text",
      children: ["Hello world!"],
    });
  };

  const trialFn = async () => {
    const designContext = await getCurrentPageContext();
    console.log(designContext);
  }

  const showAssets = async () => {
    setLoading(true);

    const assetsGetterURL = `${baseURL}assets`;
    const assetsGetterResponse = await fetch(assetsGetterURL);
    const assetsGetter = await assetsGetterResponse.json();

    setAssets(assetsGetter.assets);
    setLoading(false);
  }

  const addAssetToDesign = async (assetIndex: number) => {
    const asset:{ mimeType: ImageMimeType, path: string, width: number, height: number } = assets[assetIndex];
    const assetURL = `${baseURL}${asset.path}`;
    const assetFetchResponse:Response = await fetch(assetURL);
    const assetAsBlob:Blob = await assetFetchResponse.blob();
    const assetAsBase64:string = await new Promise( ( onSuccess, onError ) => {
      try {
        var reader = new FileReader();
        reader.onload = function(this:FileReader){ 
          onSuccess( this.result ); 
        }
        reader.readAsDataURL( assetAsBlob );
      } catch( e ) {
        onError( e );
      }
    } );

    // const imageUploadResult = await upload({
    //   type: "image",
    //   mimeType: asset.mimeType,
    //   url: assetAsBase64,
    //   thumbnailUrl: assetAsBase64,
    //   // aiDisclosure: "app_generated"
    //   aiDisclosure: "none"
    // });

    // console.log( imageUploadResult.ref );

    // get current design size
    const designContext = await getCurrentPageContext();
    const designDimension = designContext.dimensions ?? { width: 1, height: 1 };
    
    var elementWidth, elementHeight;
    if( asset.width < asset.height ) {
      elementWidth = designDimension.width;
      elementHeight = designDimension.width / asset.width * asset.height;
    } else {
      elementWidth = designDimension.height / asset.height * asset.width;
      elementHeight = designDimension.height;
    }
    
    // add element to design with proper ratio
    await addElementAtPoint ({
      type: "image",
      // ref: imageUploadResult.ref,
      dataUrl: assetAsBase64,
      altText: {
        text: `Example image no ${assetIndex}`,
        decorative: false,
      },
      top: 0,
      left: 0,
      width: elementWidth,
      height: elementHeight,
    });
  }

  // detecting change in useState variables ( draft )
  React.useEffect( () => {
    // use IIFE coz useEffect do not support async
    // need to be async so the component loaded as it ordered
    // the texts should be the last to add, to be in the front most layer
    // prone to wrong component order from the API
    (async () => {
      // place first asset of each component in the design
      if( draft !== null ) {
        for( const component of draft.components ) {
          const componentIndex = draft.components.indexOf(component);

          await addDraftAssetToDesign( componentIndex, 0 );
        }
      }
    })();
  }, [draft] );

  const loadDraft = async () => {
    setLoading(true);

    try {
      const draftGetterURL = `${baseApiURL}/draft/1739239508/0`;
      const draftGetterResponse = await fetch(draftGetterURL);
      const draftGetter = await draftGetterResponse.json();

      setDraft(draftGetter.data);
    } catch( error ) {
      console.log( error );
    }

    setLoading(false);
  }

  const addDraftAssetToDesign = async (componentIndex: number, assetIndex: number) => {
    if( draft === null ) return;

    const component = draft.components[componentIndex];
    const component_assets = component.assets;

    const designContext = await getCurrentPageContext();
    const designDimension = designContext.dimensions ?? { width: 1, height: 1 };

    const draftWidth = draft.width;
    const draftHeight = draft.height;

    const widthRatio = designDimension.width / draftWidth;
    const heightRatio = designDimension.height / draftHeight;
    
    const assetX = component.placement.x * widthRatio;
    const assetY = component.placement.y * heightRatio;

    if( component.type == "text" ) {
      const componentText = component.text;
      const componentSize = component.font_size * widthRatio;
      const componentWeight = fontWeights[component.font_weight];
      const componentColor = component.font_color;

      const asset_x = component.placement.x * widthRatio;
      const asset_y = component.placement.y * heightRatio;

      // add element to design with proper ratio
      await addElementAtPoint ({
        type: "text",
        children: [componentText],
        fontSize: componentSize,
        color: componentColor,
        fontWeight: componentWeight,
        top: assetY,
        left: assetX
      });
    } else {
      const asset = component_assets[assetIndex];
      const assetURL = `${baseURL}${asset.path}`;
      const assetFetchResponse:Response = await fetch(assetURL);
      const assetAsBlob:Blob = await assetFetchResponse.blob();
      const assetAsBase64:string = await new Promise( ( onSuccess, onError ) => {
        try {
          var reader = new FileReader();
          reader.onload = function(this:FileReader){ 
            // console.log( this )
            onSuccess( this.result ); 
          }
          reader.readAsDataURL( assetAsBlob );
        } catch( e ) {
          onError( e );
        }
      } );

      var assetWidth, assetHeight;
      if( component.type === "background" ) {
        // background
        const assetShortestSide = Math.min( asset.width, asset.height );
        const designShortestSide = Math.min( designDimension.width, designDimension.height );
        const assetDimensionRatio = designShortestSide / assetShortestSide;

        assetWidth = asset.width * assetDimensionRatio;
        assetHeight = asset.height * assetDimensionRatio;
      } else {
        // foreground
        const assetRatio = asset.width / asset.height;
        const assetLongestSide = Math.max( asset.width, asset.height );
        const assetRatioMultiplier = assetWidth > assetHeight ? widthRatio : heightRatio;
        
        assetWidth = component.dimension.width * assetRatioMultiplier;
        assetHeight = component.dimension.height * assetRatioMultiplier;
      }
      
      // add element to design with proper ratio
      await addElementAtPoint ({
        type: "image",
        // ref: imageUploadResult.ref,
        dataUrl: assetAsBase64,
        altText: {
          text: `Asset image`,
          decorative: false,
        },
        top: assetY,
        left: assetX,
        width: assetWidth,
        height: assetHeight,
      });
    }
  }

  const intl = useIntl();

  return (
    <div className={styles.scrollContainer}>
      <Rows spacing="2u">
        
        {draft === null ? (
          <Button variant="primary" onClick={loadDraft} stretch>
            {loading ? "Loading..." : "Show Draft"}
          </Button>
        ) : (
          // <Masonry 
          //   key={`masonry-assets`}
          //   targetRowHeightPx={100}>
          //   {assets.map( ( asset: { mimeType: ImageMimeType, path: string, width: number, height: number }, assetIndex: number ) => (              
          //     <MasonryItem 
          //       key={`masonry-asset-${assetIndex}`}
          //       targetHeightPx={100}
          //       targetWidthPx={100 * asset.width / asset.height}
          //     >
          //       <ImageCard 
          //         key={`asset-${assetIndex}`}
          //         alt={`Image ${assetIndex}`}
          //         onClick={ addAssetToDesign.bind(null, assetIndex) }
          //         // onClick={ trialFn }
          //         thumbnailUrl={`${baseURL}${asset.path}`} />
          //     </MasonryItem>
          //   ) )}
          // </Masonry>
          
          <Accordion 
            key={`accordion-draft`}
          >
            {draft.components.map( ( component: any, componentIndex: number ) => (
              <AccordionItem 
                key={`accordion-item-${componentIndex}`}
                title={component.name}
              >
                {component.type !== "text" && component.assets.length > 0 ? (
                  <Masonry 
                    key={`masonry-assets`}
                    targetRowHeightPx={100}>
                    {component.assets.map( ( asset: any, assetIndex: number ) => (              
                      <MasonryItem 
                        key={`masonry-asset-${assetIndex}`}
                        targetHeightPx={100}
                        targetWidthPx={100 * asset.ratio}
                      >
                        <ImageCard 
                          key={`${component.name}_${assetIndex}`}
                          alt={`${component.name}_${assetIndex}`}
                          onClick={ addDraftAssetToDesign.bind(null, componentIndex, assetIndex) }
                          thumbnailUrl={`${baseURL}${asset.path}`} />
                      </MasonryItem>
                    ) )}
                  </Masonry>
                ) : (
                  <Text>
                    {`Component ${component.name}`}
                  </Text>
                )}
              </AccordionItem>  
            ))}
          </Accordion>
        )}
      </Rows>
    </div>
  );
};
