import { useState, useEffect, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import SaveBar from '../components/common/SaveBar';

const WEIGHTS = [
    { label: 'Normal', value: 'normal' }, { label: 'Bold', value: 'bold' },
    { label: '100', value: '100' }, { label: '200', value: '200' },
    { label: '300', value: '300' }, { label: '400', value: '400' },
    { label: '500', value: '500' }, { label: '600', value: '600' },
    { label: '700', value: '700' }, { label: '800', value: '800' },
    { label: '900', value: '900' },
];
const STYLES = [
    { label: 'Normal', value: 'normal' },
    { label: 'Italic', value: 'italic' },
    { label: 'Oblique', value: 'oblique' },
];
const ROLES = [
    { label: 'Headings', value: 'heading' },
    { label: 'Body', value: 'body' },
    { label: 'Accent', value: 'accent' },
];
const ROLE_LABEL = { heading: 'Headings', body: 'Body', accent: 'Accent' };

const UploadIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="28" height="28">
        <path d="M12 16V4M8 8l4-4 4 4" /><path d="M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" />
    </svg>
);

const PlusIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 5v14M5 12h14" />
    </svg>
);

const TrashIcon = () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6" />
    </svg>
);

const CustomFonts = () => {
    const [fonts, setFonts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [baseline, setBaseline] = useState('[]');
    const [dragging, setDragging] = useState(false);
    const [showForm, setShowForm] = useState(false);
    const [newFont, setNewFont] = useState({ name: '', weight: 'normal', style: 'normal', role: 'heading', url: '', fileName: '' });

    useEffect(() => {
        apiFetch({ path: '/wp/v2/settings' }).then((settings) => {
            const saved = settings.storebuild_custom_fonts || [];
            setFonts(saved);
            setBaseline(JSON.stringify(saved));
            setLoading(false);
        });
    }, []);

    const dirty = JSON.stringify(fonts) !== baseline;

    const openMediaPicker = () => {
        if (typeof wp === 'undefined' || !wp.media) return;
        const frame = wp.media({
            title: __('Upload Font File', 'shopbuild'),
            button: { text: __('Use this font', 'shopbuild') },
            multiple: false,
        });
        frame.on('select', () => {
            const att = frame.state().get('selection').first().toJSON();
            const guessedName = (att.filename || att.url.split('/').pop()).replace(/\.[^.]+$/, '').replace(/[-_]/g, ' ');
            setNewFont(f => ({ ...f, url: att.url, id: att.id, fileName: att.filename || att.url.split('/').pop(), name: f.name || guessedName }));
            setShowForm(true);
        });
        frame.open();
    };

    const onDragOver = (e) => { e.preventDefault(); setDragging(true); };
    const onDragLeave = () => setDragging(false);
    const onDrop = (e) => { e.preventDefault(); setDragging(false); openMediaPicker(); };

    const addFont = () => {
        if (!newFont.name || !newFont.url) return;
        const updated = [...fonts, { ...newFont }];
        setFonts(updated);
        setNewFont({ name: '', weight: 'normal', style: 'normal', role: 'heading', url: '', fileName: '' });
        setShowForm(false);
    };

    const deleteFont = (index) => setFonts(fonts.filter((_, i) => i !== index));

    const handleSave = () => {
        setSaving(true);
        apiFetch({
            path: '/wp/v2/settings',
            method: 'POST',
            data: { storebuild_custom_fonts: fonts },
        }).then(() => setBaseline(JSON.stringify(fonts)))
          .finally(() => setSaving(false));
    };

    if (loading) return <div className="strb-loader">{__('Loading…', 'shopbuild')}</div>;

    return (
        <div className="strb-fonts">
            {/* ── Header card ── */}
            <div className="strb-fonts-headcard">
                <div className="strb-fonts-headinfo">
                    <h2>{__('Custom Fonts', 'shopbuild')}</h2>
                    <p>{__('Upload your brand typefaces and use them anywhere in the builder.', 'shopbuild')}</p>
                </div>
                <button type="button" className="strb-btn-fill" onClick={openMediaPicker}>
                    <PlusIcon />
                    {__('Add Font', 'shopbuild')}
                </button>
            </div>

            {/* ── Drop zone ── */}
            <div
                className={`strb-fonts-dropzone${dragging ? ' is-dragging' : ''}`}
                onClick={openMediaPicker}
                onDragOver={onDragOver}
                onDragLeave={onDragLeave}
                onDrop={onDrop}
                role="button"
                tabIndex={0}
                onKeyDown={(e) => e.key === 'Enter' && openMediaPicker()}
            >
                <span className="strb-fonts-dropico"><UploadIcon /></span>
                <strong>{__('Drop font files here, or click to upload', 'shopbuild')}</strong>
                <span>{__('Supports .woff2, .woff, .ttf and .otf — add multiple weights per family.', 'shopbuild')}</span>
            </div>

            {/* ── Inline form (shown after file is picked) ── */}
            {showForm && (
                <div className="strb-fonts-panel">
                    <h3 className="strb-fonts-h">{__('Font Details', 'shopbuild')}</h3>
                    <div className="strb-fonts-form">
                        <div className="strb-field strb-field--span2">
                            <label>{__('Font Name', 'shopbuild')}</label>
                            <input type="text" value={newFont.name} placeholder="e.g. Clash Display"
                                onChange={e => setNewFont(f => ({ ...f, name: e.target.value }))} />
                            <span className="hint">{__('Enter the font family name (e.g. My Custom Font)', 'shopbuild')}</span>
                        </div>
                        <div className="strb-field">
                            <label>{__('Font Weight', 'shopbuild')}</label>
                            <select value={newFont.weight} onChange={e => setNewFont(f => ({ ...f, weight: e.target.value }))}>
                                {WEIGHTS.map(w => <option key={w.value} value={w.value}>{w.label}</option>)}
                            </select>
                        </div>
                        <div className="strb-field">
                            <label>{__('Font Style', 'shopbuild')}</label>
                            <select value={newFont.style} onChange={e => setNewFont(f => ({ ...f, style: e.target.value }))}>
                                {STYLES.map(s => <option key={s.value} value={s.value}>{s.label}</option>)}
                            </select>
                        </div>
                        <div className="strb-field">
                            <label>{__('Role', 'shopbuild')}</label>
                            <select value={newFont.role} onChange={e => setNewFont(f => ({ ...f, role: e.target.value }))}>
                                {ROLES.map(r => <option key={r.value} value={r.value}>{r.label}</option>)}
                            </select>
                        </div>
                        <div className="strb-field">
                            <label>{__('File', 'shopbuild')}</label>
                            <span className="strb-fname">{newFont.fileName}</span>
                        </div>
                    </div>
                    <div className="strb-fonts-actions">
                        <button type="button" className="strb-btn-fill" onClick={addFont}>{__('Add Font', 'shopbuild')}</button>
                        <button type="button" className="strb-btn-ghost" onClick={() => setShowForm(false)}>{__('Cancel', 'shopbuild')}</button>
                    </div>
                </div>
            )}

            {/* ── Font list ── */}
            <div className="strb-fonts-panel">
                {fonts.length === 0 ? (
                    <div className="strb-fonts-empty">
                        <div className="ic">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 7V5h16v2" /><path d="M12 5v15M9 20h6" /></svg>
                        </div>
                        <h4>{__('No custom fonts yet', 'shopbuild')}</h4>
                        <p>{__('Upload a font above to use it across the builder.', 'shopbuild')}</p>
                    </div>
                ) : (
                    <div className="strb-fontlist">
                        {fonts.map((font, index) => (
                            <div className="strb-fontrow" key={index}>
                                <div className="strb-fontrow-aa" style={{ fontFamily: font.name, fontWeight: font.weight, fontStyle: font.style }}>Aa</div>
                                <div className="strb-fontrow-meta">
                                    <strong>{font.name}</strong>
                                    <span className="strb-fontrow-sub">{font.weight} · {font.style}</span>
                                </div>
                                <div className="strb-fontrow-tags">
                                    {font.role && <span className="strb-tag-role">{ROLE_LABEL[font.role] || font.role}</span>}
                                    <span className="strb-tag-loaded">{__('Loaded', 'shopbuild')}</span>
                                </div>
                                <button type="button" className="strb-iconbtn" onClick={() => deleteFont(index)} aria-label={__('Delete font', 'shopbuild')}>
                                    <TrashIcon />
                                </button>
                            </div>
                        ))}
                    </div>
                )}
            </div>

            <SaveBar visible={dirty} saving={saving} onSave={handleSave} />
        </div>
    );
};

export default CustomFonts;
