import CreatableSelect from "react-select/creatable";
import {showProModal} from "../../includes/ProModal";

const {useState} = React;
const {FormToggle} = wp.components;

/* ------------------------------------------------------------------
 * Color utilities
 * ------------------------------------------------------------------ */
const MODERN_COLORS = [
    '#22c55e', '#16a34a', '#4ade80',
    '#ef4444', '#dc2626',
    '#f59e0b', '#eab308', '#fde047',
    '#3b82f6', '#2563eb', '#60a5fa',
    '#a855f7', '#8b5cf6', '#c084fc',
    '#ec4899', '#f472b6',
    '#10b981', '#0ea5e9', '#06b6d4', '#14b8a6',
];

const generateRandomColor = () => {
    const hue = Math.floor(Math.random() * 360);
    return `hsl(${hue}, 70%, 60%)`;
};

const getUniqueColor = (usedColors = []) =>
    MODERN_COLORS.find(c => !usedColors.includes(c)) || generateRandomColor();

/* ------------------------------------------------------------------
 * Default tag options
 * ------------------------------------------------------------------ */
const DEFAULT_TAGS = [
    {label: wp.i18n.__('Approved', 'integrate-google-drive'), value: 'approved', color: '#22c55e'},
    {label: wp.i18n.__('Rejected', 'integrate-google-drive'), value: 'rejected', color: '#ef4444'},
    {label: wp.i18n.__('Pending', 'integrate-google-drive'), value: 'pending', color: '#f59e0b'},
    {label: wp.i18n.__('Needs Review', 'integrate-google-drive'), value: 'needs_review', color: '#3b82f6'},
    {label: wp.i18n.__('Favorite', 'integrate-google-drive'), value: 'favorite', color: '#ec4899'},
    {label: wp.i18n.__('Retouch Needed', 'integrate-google-drive'), value: 'retouch_needed', color: '#a855f7'},
    {label: wp.i18n.__('Final Selection', 'integrate-google-drive'), value: 'final_selection', color: '#10b981'},
    {label: wp.i18n.__('Confidential', 'integrate-google-drive'), value: 'confidential', color: '#64748b'},
    {label: wp.i18n.__('Requires Signature', 'integrate-google-drive'), value: 'requires_signature', color: '#0f172a'},
];

/* ------------------------------------------------------------------
 * react-select color styles
 * ------------------------------------------------------------------ */
const tagSelectStyles = {
    option: (base, state) => {
        const {data, isFocused, isSelected} = state;

        return {
            ...base,
            backgroundColor: isSelected
                ? data.color
                : isFocused
                    ? `${data.color}33`
                    : 'transparent',
            color: isSelected ? '#fff' : '#111',
            cursor: 'pointer',
        };
    },

    singleValue: (base, {data}) => ({
        ...base,
        color: data.color,
        fontWeight: 600,
    }),

    multiValue: (base, {data}) => ({
        ...base,
        backgroundColor: `${data.color}22`,
        borderRadius: 6,
    }),

    multiValueLabel: (base, {data}) => ({
        ...base,
        color: data.color,
        fontWeight: 500,
    }),

    multiValueRemove: (base, {data}) => ({
        ...base,
        color: data.color,
        ':hover': {
            backgroundColor: data.color,
            color: '#fff',
        },
    }),
};

const {isPro} = igd;

/* ------------------------------------------------------------------
 * Component
 * ------------------------------------------------------------------ */
export default function ProofingSettings({data, setData}) {

    const {
        photoProofBtnText = wp.i18n.__('Submit Selections', 'integrate-google-drive'),
        photoProofMaxSelection,
        reviewEnableTags,
        reviewTags = DEFAULT_TAGS.slice(0, 4),
    } = data;

    // unique tag options default and reviewTags
    const initialOptions = [...DEFAULT_TAGS];

    reviewTags.forEach(tag => {
        if (!initialOptions.find(o => o.value === tag.value)) {
            initialOptions.push(tag);
        }
    });

    const [options, setOptions] = useState(initialOptions);

    /* ------------------------------------------------------------------
     * Handlers
     * ------------------------------------------------------------------ */
    const updateData = (updates) => {
        if (!isPro) {
            showProModal(
                wp.i18n.__('Upgrade to PRO to enable photo proofing', 'integrate-google-drive')
            );
            return;
        }

        setData(prev => ({...prev, ...updates}));
    };

    const handleTagChange = (selected) => {

        if (!isPro) {
            showProModal(
                wp.i18n.__('Upgrade to PRO to enable photo proofing', 'integrate-google-drive')
            );
            return;
        }

        setData(prev => ({
            ...prev,
            reviewTags: selected || [],
        }));
    };

    const handleCreateTag = (inputValue) => {
        const usedColors = options.map(o => o.color);
        const color = getUniqueColor(usedColors);

        const newTag = {
            label: inputValue,
            value: inputValue.toLowerCase().replace(/\s+/g, '_'),
            color,
        };

        setOptions(prev => [...prev, newTag]);

        setData(prev => ({
            ...prev,
            reviewTags: [...(prev.reviewTags || []), newTag],
        }));
    };

    /* ------------------------------------------------------------------
     * Render
     * ------------------------------------------------------------------ */
    return (
        <div className="igd-settings-body">

            <div className="igd-settings-body-header">
                <h3 className="igd-settings-body-title">
                    {wp.i18n.__('Photo & File Proofing Settings', 'integrate-google-drive')}
                </h3>

                <p>{wp.i18n.__('Enable file proofing in the Gallery and Review & Approve modules to let clients review, select, and approve files. Manage the global proofing settings here.', 'integrate-google-drive')}</p>
            </div>

            {/* Button Text */}
            <div className="settings-field">
                <h4 className="settings-field-label">
                    {wp.i18n.__('Button Text', 'integrate-google-drive')}
                </h4>
                <div className="settings-field-content">
                    <input
                        type="text"
                        value={photoProofBtnText}
                        onChange={e => {

                            if (!isPro) {
                                showProModal(
                                    wp.i18n.__('Upgrade to PRO to enable photo proofing', 'integrate-google-drive')
                                );
                                return;
                            }

                            updateData({photoProofBtnText: e.target.value})
                        }}
                        className={`${!isPro ? 'disabled pro-feature' : ''}`}
                    />

                    <p className="description">
                        {wp.i18n.__(
                            'Enter the text for the proofing submit button.',
                            'integrate-google-drive'
                        )}
                    </p>
                </div>
            </div>

            {/* Max Selection */}
            <div className="settings-field">
                <h4 className="settings-field-label">
                    {wp.i18n.__('Maximum Selection', 'integrate-google-drive')}
                </h4>

                <div className="settings-field-content">
                    <input
                        type="number"
                        min={0}
                        value={photoProofMaxSelection}
                        onChange={e => {

                            if (!isPro) {
                                showProModal(
                                    wp.i18n.__('Upgrade to PRO to enable photo proofing', 'integrate-google-drive')
                                );
                                return;
                            }

                            updateData({photoProofMaxSelection: e.target.value})
                        }}
                        className={`${!isPro ? 'disabled pro-feature' : ''}`}
                    />
                    <p className="description">
                        {wp.i18n.__(
                            'Enter the maximum number of items that can be selected. Leave empty for no limit.',
                            'integrate-google-drive'
                        )}
                    </p>
                </div>
            </div>

            {/* Enable Tags */}
            <div className="settings-field">
                <h4 className="settings-field-label">
                    {wp.i18n.__('Enable Tags', 'integrate-google-drive')}
                </h4>

                <div className="settings-field-content">
                    <FormToggle
                        checked={reviewEnableTags}
                        onChange={() => {

                            if (!isPro) {
                                showProModal(
                                    wp.i18n.__('Upgrade to PRO to enable photo proofing', 'integrate-google-drive')
                                );
                                return;
                            }

                            setData(prev => ({
                                ...prev,
                                reviewEnableTags: !reviewEnableTags,
                            }))
                        }}
                        className={`${!isPro ? 'disabled pro-feature' : ''}`}
                    />

                    <p className="description">
                        {wp.i18n.__(
                            'Allow users to apply tags to their selections.',
                            'integrate-google-drive'
                        )}
                    </p>

                    {reviewEnableTags && (
                        <div className="settings-field-sub">
                            <div className="settings-field">

                                <h4 className="settings-field-label">
                                    {wp.i18n.__('Available Tags', 'integrate-google-drive')}
                                </h4>

                                <CreatableSelect
                                    isMulti
                                    options={options}
                                    value={reviewTags}
                                    styles={tagSelectStyles}
                                    className={`igd-select  ${!isPro ? 'disabled pro-feature' : ''}`}
                                    classNamePrefix={`igd-select`}
                                    onChange={handleTagChange}
                                    onCreateOption={handleCreateTag}
                                    placeholder={wp.i18n.__(
                                        'Create and select tags users can apply.',
                                        'integrate-google-drive'
                                    )}
                                    isClearable={false}
                                />

                                <p className="description">
                                    {wp.i18n.__(
                                        'Create and manage the tags available for proofing.',
                                        'integrate-google-drive'
                                    )}
                                </p>

                            </div>
                        </div>
                    )}
                </div>
            </div>

        </div>
    );
}
