import React, {FC} from "react";
import {Button} from "./Button";
import {__, CouponsPlus} from "../../globals";
import {CustomVariationField} from "./CustomVariationField";
import {AttributesRenderer} from "./Attributes";
import classNames from "classnames";

export type CustomAttribute = {
    id: string, // eg: 1520 (id of attr with name: 'pa_color')
    values: string[], // string of ids
    // eg: [
    //  1679, // id is 1679 of the value 'Red' {id: 1679, name: 'Red'}
    //  1578, // id is 1578 of the value 'Blue' {id: 1578, name: 'Blue'}
    // ]
    //
};
export type CustomAttributeOption = {
    type: 'any' | 'allowed' | 'excluded',
    attribute: CustomAttribute
};

export type CustomVariation = CustomAttributeOption[]

export type AttributeFieldsProps = {
    variations: CustomVariation[],
    onNewVariation: (variation: CustomVariation) => void,
    onRemoveVariation: (variationIndex: number) => void,
    onVariationChange: (variationIndex: number, attributeIndex: number, attribute: CustomAttributeOption | false) => void,
    onNewAttribute: (variationIndex: number, attribute: CustomAttributeOption) => void,
    inclusionType?: "allowed" | "forbidden"
}

function findAvailableAttribute(allAttributes: typeof CouponsPlus.attributes, existingVariations: CustomVariation) {
    return allAttributes.find(({id}) => {
        return !existingVariations.find(({attribute}) => {
            return attribute.id === id
        });
    });
}

const createDefaultAttribute = (existingVariations?: CustomVariation): CustomAttributeOption | undefined => {
    // get all the avaibale attributes
    const allAttributes = CouponsPlus.attributes || []
    const idsFromExistingVariations = existingVariations?.map(variation => variation.attribute.id) || [];

    const firstAvailableAttribute = !existingVariations?.length ? allAttributes[0]! : findAvailableAttribute(allAttributes, existingVariations)

    if (!firstAvailableAttribute) {
        console.warn('No available attributes found in the store.');
        return
    }

    return {
        type: 'allowed',
        attribute: {
            id: firstAvailableAttribute.id,
            values: [] // get the ids of the values
        }
    }
};

const storeHasAttributes = (): boolean => {
    return CouponsPlus.attributes.length > 0;
}

export const AttributeFields: FC<AttributeFieldsProps> = ({
                                                              variations = [],
                                                              onNewVariation,
                                                              onVariationChange,
                                                              onNewAttribute,
                                                              onRemoveVariation,
                                                              inclusionType
                                                          },) => {
    if (!storeHasAttributes()) {
        return <div className="text-center text-3x text-gray-700">
            {__('No attributes found in the store. Please add attributes to use this feature (WordPress Admin > Products > Attributes).')}
        </div>;
    }
    const hasVariations = !!variations.length
    // button on click will add a variation with the first avaiblae attributes and type sot to any
    // eg: click button and it will add a variation with one attribute (color) and type set to any
    return <div
        className={classNames('gap-3 --mt-5 w-full flex flex-col items-center', {
            'border-px border-gray-200 border-opacity-80 rounded-1 p-6': !hasVariations,
        })}>
        {!hasVariations && <NoVariationsIcon/>}
        {hasVariations &&
            <p className="w-full text-left text-gray-450 text-base">{inclusionType === 'allowed' ? __('Will match any of the following variations. Each variation represents a group of products to match.') : __('Will exclude any of the following variations. Each variation represents a group of products to match.')}</p>}
        {
            variations?.map((variation, index) => <div className="space-y-1 w-full">
                    <div className="flex justify-between items-center">
                        <p className="text-smaller-1 text-gray-400 space-x-1 flex items-center">
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                 className="min-w-3 min-h-3 max-w-3 max-h-3">
                                <path
                                    d="M11.25 5.337c0-.355-.186-.676-.401-.959a1.647 1.647 0 0 1-.349-1.003c0-1.036 1.007-1.875 2.25-1.875S15 2.34 15 3.375c0 .369-.128.713-.349 1.003-.215.283-.401.604-.401.959 0 .332.278.598.61.578 1.91-.114 3.79-.342 5.632-.676a.75.75 0 0 1 .878.645 49.17 49.17 0 0 1 .376 5.452.657.657 0 0 1-.66.664c-.354 0-.675-.186-.958-.401a1.647 1.647 0 0 0-1.003-.349c-1.035 0-1.875 1.007-1.875 2.25s.84 2.25 1.875 2.25c.369 0 .713-.128 1.003-.349.283-.215.604-.401.959-.401.31 0 .557.262.534.571a48.774 48.774 0 0 1-.595 4.845.75.75 0 0 1-.61.61c-1.82.317-3.673.533-5.555.642a.58.58 0 0 1-.611-.581c0-.355.186-.676.401-.959.221-.29.349-.634.349-1.003 0-1.035-1.007-1.875-2.25-1.875s-2.25.84-2.25 1.875c0 .369.128.713.349 1.003.215.283.401.604.401.959a.641.641 0 0 1-.658.643 49.118 49.118 0 0 1-4.708-.36.75.75 0 0 1-.645-.878c.293-1.614.504-3.257.629-4.924A.53.53 0 0 0 5.337 15c-.355 0-.676.186-.959.401-.29.221-.634.349-1.003.349-1.036 0-1.875-1.007-1.875-2.25s.84-2.25 1.875-2.25c.369 0 .713.128 1.003.349.283.215.604.401.959.401a.656.656 0 0 0 .659-.663 47.703 47.703 0 0 0-.31-4.82.75.75 0 0 1 .83-.832c1.343.155 2.703.254 4.077.294a.64.64 0 0 0 .657-.642Z"/>
                            </svg>
                            <span className="flex items-center space-x-1">
                            <span>{__('Custom Variation #*').replace('*', index + 1)}</span>
                            <span
                                className="text-smaller-2 text-gray-300">{__('(All attributes in this variation must match)')}</span>
                        </span>
                        </p>
                        <button onClick={() => onRemoveVariation(index)}>
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                 className="min-w-[18px] min-h-[18px] max-w-[18px] max-h-[18px]">
                                <path fillRule="evenodd"
                                      d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-1.72 6.97a.75.75 0 1 0-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 1 0 1.06 1.06L12 13.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L13.06 12l1.72-1.72a.75.75 0 1 0-1.06-1.06L12 10.94l-1.72-1.72Z"
                                      clipRule="evenodd"/>
                            </svg>
                        </button>
                    </div>
                    <CustomVariationField customVariation={variation}
                                          onAttributeChange={(attributeIndex, attribute) => {
                                              onVariationChange(index, attributeIndex, attribute);
                                          }}
                                          canCreateNewAttribute={!!createDefaultAttribute(variation)}
                                          onNewAttribute={() => {
                                              const attribute = createDefaultAttribute(variation);
                                              if (!attribute) {
                                                  console.warn('No available attribute to add.');
                                                  return;
                                              }
                                              onNewAttribute(index, attribute);
                                          }}
                                          onRemoveAttribute={(attributeIndex) => {
                                              onVariationChange(index, attributeIndex, false)
                                          }}
                    />
                <div className="flex w-full items-center justify-center pt-3"><ANDORLabel/></div>
                </div>
            )}
        <Button preset={'blue'} onClick={() => onNewVariation([createDefaultAttribute()!])}>
            {!hasVariations? __('Add custom variation') : __('Add another custom variation.')}
        </Button>
    </div>
}

function NoVariationsIcon() {
    return <svg width="438" height="483" viewBox="0 0 438 483" fill="none" xmlns="http://www.w3.org/2000/svg"
                className="w-40 h-40">
        <path
            d="M280.062 295.605C279.004 295.925 277.975 296.285 276.975 296.698C276.438 296.915 275.862 297.018 275.283 296.998C274.704 296.979 274.135 296.839 273.614 296.586C273.092 296.334 272.629 295.975 272.255 295.533C271.881 295.09 271.604 294.574 271.442 294.018L254.922 238.513L66.7705 294.506L111.627 445.241C113.197 450.51 116.796 454.94 121.631 457.556C126.467 460.172 132.143 460.76 137.412 459.192L285.834 415.015C291.103 413.445 295.532 409.847 298.148 405.011C300.764 400.176 301.353 394.5 299.784 389.23L289.182 353.593C289.014 353.038 288.965 352.454 289.036 351.879C289.108 351.304 289.299 350.751 289.597 350.254C289.896 349.758 290.295 349.329 290.769 348.996C291.243 348.663 291.782 348.433 292.35 348.32C293.422 348.12 294.484 347.864 295.529 347.553C311.108 342.903 320.268 327.528 316.002 313.177C311.735 298.825 295.64 290.972 280.062 295.605Z"
            fill="#99ADF9"/>
        <g style={{mixBlendMode: "multiply"}} opacity="0.25">
            <path
                d="M229.741 437.173C229.741 437.173 147.421 460.279 129.291 446.863C114.016 435.587 113.312 423.961 91.631 378.093C91.3868 417.619 112.958 482.489 112.958 482.489L229.741 437.173Z"
                fill="#99ADF9"/>
        </g>
        <g style={{mixBlendMode: "multiply"}} opacity="0.25">
            <path
                d="M136.9 281.097C136.9 281.097 144.934 319.553 174.049 310.892C203.165 302.232 188.837 265.629 188.837 265.629L136.9 281.097Z"
                fill="#99ADF9"/>
        </g>
        <path
            d="M204.154 67.9214L35.8588 117.992C30.5905 119.561 26.1612 123.158 23.545 127.993C20.9288 132.827 20.3401 138.503 21.9083 143.771L66.7708 294.506L131.338 275.325C131.848 275.171 132.385 275.125 132.913 275.191C133.442 275.256 133.951 275.431 134.407 275.705C134.864 275.979 135.259 276.345 135.566 276.78C135.874 277.214 136.087 277.709 136.192 278.231C136.382 279.2 136.622 280.168 136.913 281.137C141.563 296.709 156.937 305.876 171.283 301.604C185.629 297.331 193.511 281.259 188.872 265.67C188.582 264.705 188.256 263.757 187.884 262.839C187.69 262.345 187.601 261.816 187.622 261.285C187.644 260.755 187.776 260.235 188.009 259.758C188.242 259.281 188.573 258.858 188.978 258.516C189.384 258.174 189.857 257.92 190.366 257.77L254.934 238.553L204.154 67.9214Z"
            fill="#FEC272"/>
        <g style={{mixBlendMode: "multiply"}} opacity="0.52">
            <path
                d="M45.3217 233.427C45.3217 233.427 22.2394 151.107 35.6261 132.977C46.9085 117.701 66.8751 108.761 90.4573 101.74C50.9309 101.496 0 116.644 0 116.644L45.3217 233.427Z"
                fill="#FEC272"/>
        </g>
        <path
            d="M204.154 67.9214L218.61 116.492C218.844 117.266 218.91 118.081 218.803 118.882C218.696 119.683 218.419 120.452 217.99 121.137C217.561 121.822 216.99 122.407 216.316 122.853C215.642 123.3 214.88 123.596 214.082 123.723C212.575 123.948 211.085 124.278 209.624 124.712C194.052 129.362 184.885 144.736 189.157 159.088C193.43 173.439 209.502 181.31 225.086 176.677C226.547 176.244 227.975 175.704 229.358 175.061C230.095 174.737 230.893 174.573 231.698 174.581C232.504 174.588 233.298 174.768 234.029 175.106C234.76 175.445 235.41 175.936 235.937 176.545C236.463 177.155 236.854 177.869 237.083 178.642L254.899 238.513L316.357 220.214C318.118 219.677 319.596 218.465 320.467 216.842C321.338 215.22 321.532 213.318 321.007 211.553L320.954 211.379C316.304 195.801 324.198 179.711 338.544 175.445C352.889 171.178 368.281 180.339 372.914 195.917L372.967 196.086C373.494 197.856 374.702 199.344 376.326 200.225C377.95 201.105 379.856 201.306 381.627 200.782L423.188 188.413C428.457 186.844 432.886 183.247 435.502 178.412C438.118 173.578 438.707 167.902 437.139 162.634L398.194 31.7664C396.625 26.4981 393.027 22.0688 388.193 19.4526C383.358 16.8364 377.683 16.2477 372.414 17.8159L204.154 67.9214Z"
            fill="#FF97C9"/>
        <g style={{mixBlendMode: "multiply"}} opacity="0.19">
            <path
                d="M209.623 124.706C209.623 124.706 193.487 133.239 199.37 153.037C205.252 172.835 219.011 175.41 228.061 177.026C211.786 191.197 163.691 171.69 163.691 171.69L181.862 122.811L209.623 124.706Z"
                fill="#FF97C9"/>
        </g>
        <g style={{mixBlendMode: "multiply"}} opacity="0.19">
            <path
                d="M425.257 122.561C425.257 122.561 399.571 41.0144 378.454 33.1498C360.655 26.5292 335.178 24.0937 311.607 31.1096C344.583 9.28289 399.379 0 399.379 0L425.257 122.561Z"
                fill="#FF97C9"/>
        </g>
        <path
            d="M89.1144 193.447C94.6104 193.447 99.0658 188.991 99.0658 183.495C99.0658 177.999 94.6104 173.544 89.1144 173.544C83.6185 173.544 79.1631 177.999 79.1631 183.495C79.1631 188.991 83.6185 193.447 89.1144 193.447Z"
            fill="#1C3177"/>
        <path
            d="M162.93 171.486C168.426 171.486 172.881 167.031 172.881 161.535C172.881 156.039 168.426 151.584 162.93 151.584C157.434 151.584 152.979 156.039 152.979 161.535C152.979 167.031 157.434 171.486 162.93 171.486Z"
            fill="#1C3177"/>
        <path
            d="M151.027 366.596C156.523 366.596 160.978 362.14 160.978 356.644C160.978 351.148 156.523 346.693 151.027 346.693C145.531 346.693 141.075 351.148 141.075 356.644C141.075 362.14 145.531 366.596 151.027 366.596Z"
            fill="#1C3177"/>
        <path
            d="M224.842 344.629C230.338 344.629 234.793 340.174 234.793 334.678C234.793 329.182 230.338 324.727 224.842 324.727C219.346 324.727 214.891 329.182 214.891 334.678C214.891 340.174 219.346 344.629 224.842 344.629Z"
            fill="#1C3177"/>
        <path
            d="M289.728 123.799C291.292 129.065 287.403 131.605 282.131 133.175C276.859 134.744 272.215 134.744 270.645 129.478C270.242 128.216 270.094 126.887 270.211 125.567C270.327 124.248 270.706 122.965 271.325 121.794C271.943 120.622 272.79 119.586 273.814 118.746C274.838 117.906 276.019 117.279 277.289 116.901C278.559 116.523 279.891 116.402 281.208 116.546C282.524 116.689 283.799 117.094 284.958 117.736C286.116 118.379 287.135 119.246 287.954 120.287C288.773 121.328 289.376 122.522 289.728 123.799V123.799Z"
            fill="#1C3177"/>
        <path
            d="M363.539 101.833C365.108 107.105 361.214 109.639 355.942 111.209C350.67 112.778 346.025 112.778 344.456 107.512C344.052 106.25 343.904 104.921 344.021 103.601C344.138 102.282 344.517 100.999 345.135 99.8274C345.754 98.6561 346.6 97.62 347.624 96.7799C348.648 95.9397 349.83 95.3124 351.1 94.9346C352.369 94.5567 353.701 94.436 355.018 94.5795C356.335 94.723 357.61 95.1278 358.768 95.7702C359.927 96.4126 360.946 97.2797 361.765 98.3207C362.584 99.3617 363.187 100.556 363.539 101.833V101.833Z"
            fill="#1C3177"/>
    </svg>;
}


export const ANDORLabel = () => <div className="flex items-center gap-0">
    <div className="h-px w-5 bg-gray-150"></div>
    <div className="text-smaller-1 text-gray-350 px-3 py-1 rounded-2 bg-gray-100">
        {__('AND / OR')}
    </div>
    <div className="h-px w-5 bg-gray-150"></div>
</div>