import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { computed, makeObservable, observable, action } from 'mobx';
import { observer, } from 'mobx-react';
import * as React from 'react';
import { Utils, emptyFunction, returnFalse, returnZero } from '../../../Utils';
import { Doc, DocListCast } from '../../../fields/Doc';
import { Id } from '../../../fields/FieldSymbols';
import { DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
import { DocumentType } from '../../documents/DocumentTypes';
import { DragManager } from '../../util/DragManager';
import { SelectionManager } from '../../util/SelectionManager';
import { StyleProp } from '../StyleProvider';
import { DocumentView } from '../nodes/DocumentView';
import { FocusViewOptions } from '../nodes/FieldView';
import './CollectionCarousel3DView.scss';
import { CollectionSubView } from './CollectionSubView';
import { ScriptField } from '../../../fields/ScriptField';

const { default: { CAROUSEL3D_CENTER_SCALE, CAROUSEL3D_SIDE_SCALE, CAROUSEL3D_TOP } } = require('../global/globalCssVariables.module.scss'); // prettier-ignore
@observer
export class CollectionCardView extends CollectionSubView() {
    // @computed get scrollSpeed() {
    //     return this.layoutDoc._autoScrollSpeed ? NumCast(this.layoutDoc._autoScrollSpeed) : 1000; //default scroll speed
    // }

    selectedNodeIndex = observable.box(-1); // -1 indicates no selection

    @action
    setSelectedNodeIndex = (index: number) => {
        console.log('hi');
        SelectionManager.DeselectAll();
        this.selectedNodeIndex.set(index);
    };

    @computed
    get rotationDegree() {
    return this.isChildContentActive() ? 30 : 0; // Rotate by 30 degrees if selected, otherwise no rotation
}



    constructor(props: any) {
        super(props);
        makeObservable(this);
    }

    private _dropDisposer?: DragManager.DragDropDisposer;

    componentWillUnmount() {
        this._dropDisposer?.();
    }

    protected createDashEventsTarget = (ele: HTMLDivElement | null) => {
        this._dropDisposer?.();
        if (ele) {
            this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.layoutDoc);
        }
    };

    centerScale = Number(CAROUSEL3D_CENTER_SCALE);
    panelWidth = () => (this._props.PanelWidth()) / this.childLayoutPairs.length;
    panelHeight = () => this.panelWidth() * 1.5;
    onChildDoubleClick = () => ScriptCast(this.layoutDoc.onChildDoubleClick);
    onChildClick = () => ScriptCast(this.rotate(3, 3));
    isContentActive = () => this._props.isSelected() || this._props.isContentActive() || this._props.isAnyChildContentActive();
    isChildContentActive = () => (this.isContentActive() ? true : false);
    
    //thid needs to be fixed
    childScreenToLocal = () =>
        this._props // document's left is the panel shifted by the doc's index * panelWidth/#docs.  But it scales by centerScale around its center, so it's left moves left by the distance of the left from the center (panelwidth/2) * the scale delta (centerScale-1)
            .ScreenToLocalTransform() // the top behaves the same way ecept it's shifted by the 'top' amount specified for the panel in css and then by the scale factor.
            // .translate(-this.panelWidth() + ((this.centerScale - 1) * this.panelWidth()) / 2,-((Number(CAROUSEL3D_TOP) / 100) * this._props.PanelHeight()) + ((this.centerScale - 1) * this.panelHeight()) / 2)
            .rotate(this.rotate(this.childLayoutPairs.length, Number(this.layoutDoc._carousel_index)))
            // .scale(1 / this.centerScale);


    //literally doesnot do anythin
    focus = (anchor: Doc, options: FocusViewOptions) => {
        const docs = DocListCast(this.Document[this.fieldKey ?? Doc.LayoutFieldKey(this.Document)]);
        if (anchor.type !== DocumentType.CONFIG && !docs.includes(anchor)) return;
        options.didMove = true;
        const target = DocCast(anchor.annotationOn) ?? anchor;
        const index = docs.indexOf(target);
        index !== -1 && (this.layoutDoc._carousel_index = index); //if index is not -1, then assign index to this.layoutDoc._carousel_index
        return undefined;
    };

    rotate = (amCards: number, index: number) => {

        const possRotate = -30 + (index * (30/((amCards - (amCards%2))/2)));

        if (amCards%2 == 0 && possRotate==0){
                console.log('whaddup')
                return possRotate + Math.abs(-30 + ((index-1) * (30/((amCards - 1)/2))))
        }
    
       return possRotate;
    }

    // translateY = (amCards: number, index: number) => {
    //     // Assuming you want a default value when index > amCards/2
    //     // Adjust the logic as necessary for your use case
    //     if (index <= amCards / 2) {
    //         return -((50 / ((amCards - (amCards % 2)) / 2)) * index);
    //     } else {
    //         // Return a default or calculated value for indices greater than amCards/2
    //         // This is just an example; adjust the logic as needed
    //         return -((50 / ((amCards - (amCards % 2)) / 2)) * (amCards - index - 1));
    //     }
    // };

    
    @computed get content() {
        // const currentIndex = NumCast(this.layoutDoc._carousel_index);
        const amCards = this.childLayoutPairs.length;
        const displayDoc = (childPair: { layout: Doc; data: Doc }) => {
            return (
                <DocumentView
                    {...this._props}
                    Document={childPair.layout}
                    TemplateDataDocument={childPair.data}
                    // onClickScript={this.toggleIcon}
                    //suppressSetHeight={true}
                    NativeWidth={returnZero}
                    NativeHeight={returnZero}
                    layout_fitWidth={undefined}
                    onDoubleClickScript={this.onChildDoubleClick}
                    renderDepth={this._props.renderDepth + 1}
                    LayoutTemplate={this._props.childLayoutTemplate}
                    LayoutTemplateString={this._props.childLayoutString}
                    focus={this.focus}
                    ScreenToLocalTransform={this.childScreenToLocal} //makes sure the box wrapper thing is in the right spot 
                    isContentActive={this.isChildContentActive}
                    isDocumentActive={this._props.childDocumentsActive?.() || this.Document._childDocumentsActive ? this._props.isDocumentActive : this.isContentActive}
                    PanelWidth={this.panelWidth}
                    PanelHeight={this.panelHeight}
                />
            );
        };

        return this.childLayoutPairs.map((childPair, index) => {

            const isSelected = this.selectedNodeIndex.get() === index;
            const rotationDegree = isSelected ? 30 : 0; // Rotate selected node by 5 degrees, for example


            return (
                <div key={childPair.layout[Id]} 
                // className={`collectionCarousel3DView-item${index === currentIndex ? '-active' : ''} ${index}`} 
                style={{ width: this.panelWidth(), height: this.panelHeight(), 
                    transform: `rotate(${this.rotate(amCards, index) + rotationDegree}deg)`,
                
        
                // translateY(${this.translateY(amCards, index)}px)`,
                }}
                onClick={() => this.setSelectedNodeIndex(index)}

 
                
                >
                    {/* {this.lol(childPair.data, index)} */}

                
                    {displayDoc(childPair)}
                </div> 
            );
        });
    }

    // lol = (d : Doc, index: number) => {
    //     if (SelectionManager.IsSelected(d)){
    //         this.setSelectedNodeIndex(index);

    //     }
    // }

    @computed get translateX() {
        const index = NumCast(this.layoutDoc._carousel_index);
        return this.panelWidth() * (1 - index);
    }

    render() {
        return (
            <div
                className="collectionCarousel3DView-outer"
                ref={this.createDashEventsTarget}
                style={{
                    background: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BackgroundColor),
                    color: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color),
                }}>
                <div className="carousel-wrapper" 
                // style={{ transform: `translateX(${this.translateX}px)` }}
                >
                    {this.content}
                </div>
                {/* {this.buttons}
                <div className="dot-bar">{this.dots}</div> */}
            </div>
        );
    }


}
