import React from 'react';
import type { IconDefinition } from '@fortawesome/fontawesome-svg-core';
import { faCartShopping, faPhone } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import styles from './ActionButtons.module.css';
import { Link } from '@inertiajs/react';

const SolidIcons = {
    faCartShopping,
    faPhone,
}

interface ButtonData {
    type: 'link';
    data: {
        name: string;
        icon: keyof typeof SolidIcons;
        btn_style: 'primary' | 'secondary';
        link: string;
        external: boolean;
        new_tab: boolean;
    };
}

interface ActionButtonsProps {
    variant?: 'default' | 'floating';
}

export const ActionButtons: React.FC<ActionButtonsProps> = ({ variant = 'default' }) => {
    const [buttons, setButtons] = React.useState<ButtonData[]>([]);

    React.useEffect(() => {
        fetch('/api/buttons')
            .then(res => res.json())
            .then(response => {
                if (response.status === 'success') {
                    setButtons(response.data);
                }
            })
            .catch(error => {
                console.error('Error fetching buttons:', error);
            });
    }, []);



    return (
        <div>
            {buttons && buttons.length > 0 && buttons.map((button, index) => {
                const icon: IconDefinition | null = button.data.icon ? (SolidIcons[button.data.icon] as IconDefinition) : null;
                const isPrimary = button.data.btn_style === 'primary';

                const buttonClass = variant === 'floating' 
                ? isPrimary ? styles['onlineorder-fixed'] : styles['phone-fixed']
                : isPrimary ? styles.onlineorder : styles.phone;

                return button.data.external ? (
                    <div className={buttonClass} key={index}>
                        <a
                            href={button.data.link}
                            target="_blank"
                            rel="noopener noreferrer"
                            className={styles['phone-link']}
                        >
                            {icon && <FontAwesomeIcon className={isPrimary ? styles['cart-icon'] : styles['phone-icon']} icon={icon} />}
                            <span>{button.data.name}</span>
                        </a>
                    </div>
                ) : (
                    <div className={buttonClass} key={index}>
                        <Link  
                            href={button.data.link}
                            className={styles['phone-link']}
                        >
                            {icon && <FontAwesomeIcon className={isPrimary ? styles['cart-icon'] : styles['phone-icon']} icon={icon} />}
                            <span>{button.data.name}</span>
                        </Link>
                    </div>
                );
            })}
        </div>
    );
};
