import React, {FC} from "react";
import {ConditionColorPalette} from "./tree/Colors";
import {NodeWithAnchors} from "./NodeWithAnchors";
import {NodeProps} from "@xyflow/react";
import {useCardRenderer} from "./tree/hooks";
import {Card} from "./tree/Card";
import {CardItem} from "./tree/CardItem";
import {useTreeNodeTestable} from "./tree/TreeHooks";
import {Anchor, TestablePartial} from "./tree/store";
import {PopupWindowStateContext, TreeContextData} from "./tree/atoms";
import {TestablesSaver} from "./tree/TestablesSaver";
import {useOpenTestablesPopupWindow} from "./tree/useOpenTestablesPopupWindow";
import {__} from "./globals";
import classNames from "classnames";
import {getTierCardColor} from "./tree/getTierCardColor";

export type TierSubchildNodeProps = {}

export const TieredSubchildNode: FC<TierSubchildNodeProps & NodeProps> = ({id}) => {
    const testableNode = useTreeNodeTestable(id)
    const branch = testableNode?.branch
    const cardRenderer = useCardRenderer(id, 'testablePartials')
    const openTestablePopupWindow = useOpenTestablesPopupWindow()
    if (!testableNode) {
        console.error('TieredSubchildNode: testableNode not found', id)
        return null;
    }
    if (!branch) {
        console.error('TieredSubchildNode: testable not found', id)
        return null;
    }
    const baseTestable = testableNode.getTestable().getParent()
    const parentCompositeData = baseTestable?.getParent()?.getData()
    const conditionPalette = (
        parentCompositeData
        && typeof parentCompositeData === 'object'
        && 'conditionColorPalette' in parentCompositeData
        && typeof parentCompositeData.conditionColorPalette === 'string'
    ) ? parentCompositeData.conditionColorPalette as ConditionColorPalette : undefined
    const color = getTierCardColor(
        baseTestable?.getMode() || 'filter',
        {
            conditionPalette,
            place: 'tier-subchild',
        }
    )
    const canRenderFilteredItemsLabel = baseTestable?.getMode() === 'filter'

    return <NodeWithAnchors data={{
        sourceAnchor: branch.isTiered() ? {
            id: 'bottom',
            position: 'bottom',
        } as Anchor : undefined
    }} color={color} right={branch.isSimple()} centerExtraAnchor={false}>
        <Card color={color}>
            <CardItem color={color}
                      position={'single'}
                      context={'tier-subchild'}
                      className={'overflow-hidden rounded-[18px]'}
                      cardRenderer={cardRenderer}
                      onClick={() => {
                          // open the testabls popup to edit ts, in TIER SUBCHILD context!
                          const context = {
                              id: 'subchild-edit',
                              scope: 'tier-subchild', // don't change it as it's used in the popup to locate the correct testable!
                              data: {
                                  componentType: baseTestable?.getTestableType() || 'filter',
                                  supportsMultipleComponents: false,
                                  supportsOptionalQuantity: false,
                                  targetType: 'testablePartial',
                                  mode: 'edit',
                                  targetId: id
                              }
                          } as PopupWindowStateContext<TreeContextData>

                          openTestablePopupWindow({
                              context,
                              onClose: (data) => {
                                  if (data.status !== 'success' || !data.components) {
                                      return
                                  }
                                  // @ts-ignore
                                  const saver = new TestablesSaver(context)

                                  // here we have the component with extra data possibly added so let's just add the expected testable partial structure,
                                  // i dont know how i feel abt this though bc if we change the partials structure there's a good chance we'll forget to change it here and only find out after trying to update a partial from the ui (bug)
                                  // let's just hope typescript catches this?
                                  saver.update<TestablePartial>(data.components.map(partialMergeWithParent => ({
                                      id: partialMergeWithParent.id as string,
                                      options: partialMergeWithParent.options,
                                  })))
                              }
                          });
                      }}
            />
        </Card>
        <div className={classNames('absolute', {
            'top-1 right-0': !branch.isTiered(),
            'left-1/2 -translate-x-1/2 pl-6 py-2': branch.isTiered(),
        })}>
            {canRenderFilteredItemsLabel && <div className={classNames('flex gap-[2px] text-purple-tint-50', {
                'flex-row items-center translate-x-full pl-2': !branch.isTiered(),
                'flex flex-col items-start': branch.isTiered(),
            })}>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor"
                     className="min-w-[10px] min-h-[10px] max-w-[10px] max-h-[10px]">
                    <path
                        d="M7.628 1.099a.75.75 0 0 1 .744 0l5.25 3a.75.75 0 0 1 0 1.302l-5.25 3a.75.75 0 0 1-.744 0l-5.25-3a.75.75 0 0 1 0-1.302l5.25-3Z"/>
                    <path
                        d="m2.57 7.24-.192.11a.75.75 0 0 0 0 1.302l5.25 3a.75.75 0 0 0 .744 0l5.25-3a.75.75 0 0 0 0-1.303l-.192-.11-4.314 2.465a2.25 2.25 0 0 1-2.232 0L2.57 7.239Z"/>
                    <path
                        d="m2.378 10.6.192-.11 4.314 2.464a2.25 2.25 0 0 0 2.232 0l4.314-2.465.192.11a.75.75 0 0 1 0 1.303l-5.25 3a.75.75 0 0 1-.744 0l-5.25-3a.75.75 0 0 1 0-1.303Z"/>
                </svg>
                {false && <p className={'text-smaller-1'}>{__('Filter items')}</p>}
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor"
                     className={classNames('h-3', {
                         '-rotate-90': !branch.isTiered(),
                     })}>
                    <path fillRule="evenodd"
                          d="M8 2a.75.75 0 0 1 .75.75v8.69l1.22-1.22a.75.75 0 1 1 1.06 1.06l-2.5 2.5a.75.75 0 0 1-1.06 0l-2.5-2.5a.75.75 0 1 1 1.06-1.06l1.22 1.22V2.75A.75.75 0 0 1 8 2Z"
                          clipRule="evenodd"/>
                </svg>
            </div>
            }        </div>
    </NodeWithAnchors>
}
