import { useEffect, useState } from 'react';
import './wizard-style.scss';
import { UserRole } from './user-role';
import { BrandAssets } from './brand-assets';
import { ApiResponse } from '../home/templates/template-editor/types/template-data-type';
import apiFetch from '@wordpress/api-fetch';
import ThemehighLogo from '../../images/themehigh-logo.svg'

interface Image {
    url: string;
    filename: string;
    id: number | null;
}
export const SetupWizard: React.FC = () => {
    const[ step, setStep ] = useState<number>(1);
    const [selectedUserRole, setSelectedUserRole] = useState<string | null>(null);
    const [email, setEmail] = useState<string>('');
    const [logoData, setLogoData] = useState<any>(null);
    const [colorData, setColorData] = useState<any>(null);
    const [activeToggle, setActiveToggle] = useState<number>(1);

    const navButtonClick = (e: React.FormEvent<HTMLButtonElement>, nav: string) => {
        e.preventDefault();
        if('next' === nav) {
            setStep(step +1);
            setActiveToggle(step +1);
        }else if('previous' === nav) {
            setStep(step - 1);
            setActiveToggle(step - 1);
        }
    };

    const handleOptionChange = (optionID: string) => {
        setSelectedUserRole(optionID);
    };
    const handleEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setEmail(event.target.value);
    };
    const handleChangeLogo = (image: Image | null) => {
        setLogoData(image);
    };
    const handleColorChange = (color: string) => {
        setColorData(color);
    };
    const handleToggleClick = (index: number) => {
        setActiveToggle(index);
        setStep(index);
    };
    const isNextButtonDisabled = step === 1 && !selectedUserRole;

    const currentPath = window.location.pathname;
    const cleanedPath = currentPath.replace(/\/index.php/, '');

    const saveData = async () => {
        const data = {
            userRole: selectedUserRole,
            userEmail: email,
            brandLogo: {
                id: logoData?.id || null,
                url: logoData?.url || '',
                filename: logoData?.filename || '',
            },
            primaryColor: colorData,
        };
        window.location.href = cleanedPath + `/admin.php?page=skyro-woocommerce-checkout-get-help`;

        try {
            const response = await apiFetch<ApiResponse>({
                path: 'thswc/brand-asset-data/brand-assets',
                method: 'POST',
                data: data,
            });

            if (response) {
                // console.log("success");
            }

        } catch (err) {
            console.error(err);
        }
    };    

    return (
        <div className='th-setup-wizard__wrapper'>
            <div className={`th-setup-wizard__col1 th-col th-setup-wizard_page_${step === 1 ? 1 : 2 }`}>
                <img className='th-logo' src={ThemehighLogo} alt="Themehigh logo" />
                {step === 1 ? (
                    <div className='content-wrapper'>
                        <h1>Welcome to <br/>SKYRO Checkout for WooCommerce</h1>
                        <p>Your journey towards reduced cart abandonment and improved conversion rates starts here.</p>
                    </div>
                ):(
                    <div className='content-wrapper'>
                        <h1>An all-in-one solution for <br/>all your checkout woes</h1>
                        <p>Our impressive range of features is designed to eliminate any checkout page issues you may encounter.</p>
                    </div>
                )}
            </div>
            <div className='th-setup-wizard__col2 th-col'>
                <form>
                    <div className='th__toggle-wrapper'>
                        <span
                            className={`th-nav-toggle ${activeToggle === 1 ? 'active' : ''}`}
                            onClick={() => handleToggleClick(1)}
                        ></span>
                        <span
                            className={`th-nav-toggle ${activeToggle === 2 ? 'active' : ''} ${isNextButtonDisabled ? 'disabled' : ''}`}
                            onClick={() => handleToggleClick(2)}
                        ></span>
                    </div>
                    {step === 1 ? (
                        <>
                            <UserRole 
                                selectedUserRole={selectedUserRole}
                                handleOptionChange={handleOptionChange}
                                handleEmailChange={handleEmailChange}
                                email={email}
                            />
                            <hr className='seperator-1'></hr>
                        </>
                    ):(
                        <>
                            <BrandAssets
                                selectedLogo={logoData}
                                handleChangeLogo={handleChangeLogo}
                                selectedColor={colorData}
                                handleColorChange={handleColorChange}
                            />
                            <hr className='seperator-1'></hr>
                        </>
                    )}
                    <div className="nav-btn-wrapper">
                        {step === 1 ? (
                            <>
                                <a 
                                    href={cleanedPath + `/admin.php?page=skyro-woocommerce-checkout-get-help` } 
                                    className='nav-btn-normal btn-skip'>Skip
                                </a>
                                <button 
                                    className={`nav-btn-highlighted ${isNextButtonDisabled ? 'disabled' : ''}`} 
                                    onClick={(e) => !isNextButtonDisabled && navButtonClick(e, 'next') }>Next 
                                    <span className="right-arrow">
                                        &#8594;
                                    </span>
                                </button>
                            </>
                        ) : (
                            <>
                                <button className='nav-btn-normal nav-btn-prev' onClick={(e) => navButtonClick(e, 'previous') }><span className="right-arrow">&#8592;</span>Previous</button>
                                <a 
                                    href={cleanedPath + `/admin.php?page=skyro-woocommerce-checkout-get-help`} 
                                    className='nav-btn-normal btn-skip'>Skip
                                </a>
                                <button className='nav-btn-highlighted' onClick={(e) => { navButtonClick(e, 'next'); saveData(); }}>Submit & Continue</button>
                            </>
                        )}
                    </div>
                </form>
            </div>
        </div>
    );
}