import React, { useState, useRef } from 'react';
import { jwtDecode } from 'jwt-decode';
import * as Kubikon3DApi from '../../api/Kubikon3DService';

/**
 * KubikonBugReportButton — плавающая кнопка справа снизу + модалка
 * для отправки баг-репорта со скриншотом. Синий wow-стиль Рублокса.
 *
 * Используется в плеере (`bugType='player'`, projectId передаётся) и в редакторе
 * (`bugType='editor'`).
 *
 * Принимает props:
 *   - bugType: 'player' | 'editor' | 'site' | 'other'
 *   - projectId: number | null  (если репорт привязан к конкретной игре)
 *   - bottomOffset: number      (отступ снизу, чтобы не наезжать на чужой UI)
 *   - rightOffset:  number
 *   - hidden:       bool        (если true — кнопка не рисуется,
 *                                 триггерится извне через [data-kubikon-bug-btn])
 */
const KubikonBugReportButton = ({
    bugType = 'site',
    projectId = null,
    bottomOffset = 16,
    rightOffset = 16,
    hidden = false,
}) => {
    const [open, setOpen] = useState(false);
    const [hover, setHover] = useState(false);

    return (
        <>
            <style>{BUG_KEYFRAMES}</style>
            <button
                data-kubikon-bug-btn
                onClick={() => setOpen(true)}
                onMouseEnter={() => setHover(true)}
                onMouseLeave={() => setHover(false)}
                title="Сообщить об ошибке"
                style={{
                    position: 'fixed',
                    bottom: bottomOffset,
                    right: rightOffset,
                    zIndex: 1500,
                    width: 52, height: 52,
                    borderRadius: '50%',
                    background: BUG.gradientBrand,
                    border: '1px solid rgba(255, 255, 255, 0.18)',
                    boxShadow: hover
                        ? '0 12px 28px rgba(51, 87, 255, 0.55), 0 0 0 6px rgba(51, 87, 255, 0.18)'
                        : '0 8px 20px rgba(51, 87, 255, 0.40)',
                    color: '#fff',
                    fontSize: 22,
                    cursor: 'pointer',
                    display: hidden ? 'none' : 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontFamily: BUG.font,
                    transform: hover ? 'translateY(-2px) scale(1.05)' : 'translateY(0) scale(1)',
                    transition: 'all 220ms cubic-bezier(0.34, 1.56, 0.64, 1)',
                    animation: hover ? 'none' : 'bugPulseRing 2.4s ease-in-out infinite',
                }}
            >
                🐛
            </button>
            {open && (
                <KubikonBugReportModal
                    bugType={bugType}
                    projectId={projectId}
                    onClose={() => setOpen(false)}
                />
            )}
        </>
    );
};

const BUG_TYPES = [
    { id: 'player', label: '🎮 Проблема в плеере', desc: 'запуск/управление/UI' },
    { id: 'editor', label: '🔨 Проблема в редакторе', desc: 'блоки/сохранение/скрипты' },
    { id: 'site',   label: '🌐 Проблема на сайте',   desc: 'страницы/ссылки' },
    { id: 'other',  label: '❓ Другое',                desc: 'что-то ещё' },
];

const KubikonBugReportModal = ({ bugType: initialType, projectId, onClose }) => {
    const [bugType, setBugType] = useState(initialType || 'site');
    const [title, setTitle] = useState('');
    const [message, setMessage] = useState('');
    const [file, setFile] = useState(null);
    const [filePreview, setFilePreview] = useState(null);
    const [submitting, setSubmitting] = useState(false);
    const [submitError, setSubmitError] = useState(null);
    const [done, setDone] = useState(false);
    const [dragOver, setDragOver] = useState(false);
    const fileInputRef = useRef(null);

    const userId = (() => {
        try {
            const t = localStorage.getItem('Authorization');
            if (!t) return null;
            return jwtDecode(t).id || null;
        } catch (e) { return null; }
    })();

    const onFileChange = (e) => {
        const f = e.target.files?.[0] || null;
        applyFile(f);
    };

    const applyFile = (f) => {
        setFile(f);
        if (f) {
            const reader = new FileReader();
            reader.onload = () => setFilePreview(reader.result);
            reader.readAsDataURL(f);
        } else {
            setFilePreview(null);
        }
    };

    const onDrop = (e) => {
        e.preventDefault();
        setDragOver(false);
        const f = e.dataTransfer?.files?.[0];
        if (f && f.type.startsWith('image/')) applyFile(f);
    };

    const submit = async () => {
        if (!message.trim() && !title.trim()) {
            setSubmitError('Опиши, что не так — хотя бы пару слов.');
            return;
        }
        setSubmitting(true);
        setSubmitError(null);
        try {
            await Kubikon3DApi.createBugReport({
                bug_type: bugType,
                title: title.trim(),
                message: message.trim(),
                url_path: window.location.pathname,
                user_agent: navigator.userAgent,
                user_id: userId,
                project_id: projectId,
                screenshot: file,
            });
            setDone(true);
        } catch (e) {
            setSubmitError(e?.response?.data?.error || e?.message || 'Ошибка сети');
            setSubmitting(false);
        }
    };

    return (
        <div onClick={onClose} style={modalBackdrop}>
            <style>{BUG_KEYFRAMES}</style>
            <div onClick={(e) => e.stopPropagation()} style={modalCard}>
                {done ? (
                    <SuccessView onClose={onClose} />
                ) : (
                    <>
                        {/* Градиентный header */}
                        <div style={{
                            background: BUG.gradientBrand,
                            padding: '20px 24px',
                            display: 'flex', alignItems: 'center',
                            justifyContent: 'space-between', gap: 12,
                            position: 'relative',
                            overflow: 'hidden',
                        }}>
                            {/* Декоративные плавающие кружки */}
                            <div style={{
                                position: 'absolute', top: -20, right: 60,
                                width: 80, height: 80, borderRadius: '50%',
                                background: 'rgba(255,255,255,0.10)',
                                pointerEvents: 'none',
                            }} />
                            <div style={{
                                position: 'absolute', bottom: -30, left: 100,
                                width: 60, height: 60, borderRadius: '50%',
                                background: 'rgba(255,255,255,0.08)',
                                pointerEvents: 'none',
                            }} />

                            <div style={{
                                display: 'inline-flex', alignItems: 'center', gap: 14,
                                position: 'relative', zIndex: 1,
                            }}>
                                <div style={{
                                    width: 44, height: 44, borderRadius: 12,
                                    background: 'rgba(255,255,255,0.18)',
                                    border: '1px solid rgba(255,255,255,0.25)',
                                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                                    fontSize: 22,
                                    animation: 'bugFloat 3.6s ease-in-out infinite',
                                }}>🐛</div>
                                <div>
                                    <h2 style={{
                                        margin: 0, fontSize: 18, fontWeight: 800, color: '#fff',
                                        letterSpacing: -0.3,
                                    }}>Сообщить об ошибке</h2>
                                    <div style={{
                                        fontSize: 12, color: 'rgba(255,255,255,0.78)',
                                        marginTop: 2, fontWeight: 600,
                                    }}>
                                        Расскажи, что пошло не так — мы исправим
                                    </div>
                                </div>
                            </div>
                            <button
                                onClick={onClose}
                                style={iconCloseBtn}
                                onMouseEnter={(e) => {
                                    e.currentTarget.style.background = 'rgba(255,255,255,0.22)';
                                }}
                                onMouseLeave={(e) => {
                                    e.currentTarget.style.background = 'rgba(255,255,255,0.10)';
                                }}
                            >×</button>
                        </div>

                        <div style={{ padding: '22px 24px' }}>
                            {/* Тип бага — карточки с иконками */}
                            <div style={field}>
                                <div style={fieldLabel}>📍 Где сломалось</div>
                                <div style={{
                                    display: 'grid',
                                    gridTemplateColumns: 'repeat(2, 1fr)',
                                    gap: 8,
                                }}>
                                    {BUG_TYPES.map(t => (
                                        <BugTypeCard
                                            key={t.id}
                                            option={t}
                                            selected={bugType === t.id}
                                            onClick={() => setBugType(t.id)}
                                        />
                                    ))}
                                </div>
                            </div>

                            {/* Заголовок */}
                            <div style={field}>
                                <div style={fieldLabel}>✏️ Заголовок (коротко)</div>
                                <FocusableInput
                                    value={title}
                                    onChange={(v) => setTitle(v)}
                                    placeholder="Например: «Не работает прыжок»"
                                    maxLength={200}
                                />
                            </div>

                            {/* Подробности */}
                            <div style={field}>
                                <div style={fieldLabel}>📝 Подробности</div>
                                <FocusableTextarea
                                    value={message}
                                    onChange={(v) => setMessage(v)}
                                    placeholder="Опиши: что делал, что ожидал, что получилось"
                                    rows={5}
                                />
                            </div>

                            {/* Скриншот — drag-and-drop зона */}
                            <div style={field}>
                                <div style={fieldLabel}>📎 Скриншот (необязательно, ≤5 МБ)</div>
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept="image/png,image/jpeg,image/gif,image/webp"
                                    onChange={onFileChange}
                                    style={{ display: 'none' }}
                                />
                                {!file ? (
                                    <button
                                        onClick={() => fileInputRef.current?.click()}
                                        onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
                                        onDragLeave={() => setDragOver(false)}
                                        onDrop={onDrop}
                                        style={{
                                            width: '100%',
                                            padding: '24px 16px',
                                            background: dragOver
                                                ? BUG.accentBg
                                                : '#fafbfd',
                                            border: dragOver
                                                ? `2px dashed ${BUG.accent}`
                                                : `2px dashed ${BUG.borderHover}`,
                                            borderRadius: 12,
                                            color: dragOver ? BUG.accent : BUG.textMuted,
                                            cursor: 'pointer',
                                            fontFamily: BUG.font,
                                            fontSize: 14, fontWeight: 700,
                                            transition: 'all 200ms ease',
                                            display: 'flex', alignItems: 'center',
                                            justifyContent: 'center', gap: 10,
                                        }}
                                    >
                                        <span style={{
                                            fontSize: 22,
                                            transform: dragOver ? 'scale(1.2)' : 'scale(1)',
                                            transition: 'transform 200ms ease',
                                        }}>📎</span>
                                        {dragOver ? 'Отпусти, и оно загрузится' : 'Выбрать или перетащить картинку'}
                                    </button>
                                ) : (
                                    <div style={{
                                        background: BUG.bgInput,
                                        border: `1px solid ${BUG.border}`,
                                        borderRadius: 12,
                                        padding: 10,
                                        display: 'flex',
                                        gap: 12,
                                        alignItems: 'center',
                                        animation: 'bugFadeInScale 220ms cubic-bezier(0.34, 1.56, 0.64, 1)',
                                    }}>
                                        {filePreview && (
                                            <img src={filePreview} alt="preview" style={{
                                                width: 88, height: 64, objectFit: 'cover',
                                                borderRadius: 8,
                                                border: `1px solid ${BUG.border}`,
                                                boxShadow: '0 4px 12px rgba(0,0,0,0.4)',
                                            }} />
                                        )}
                                        <div style={{ flex: 1, minWidth: 0 }}>
                                            <div style={{
                                                fontSize: 13, fontWeight: 700, color: BUG.text,
                                                overflow: 'hidden', textOverflow: 'ellipsis',
                                                whiteSpace: 'nowrap',
                                            }}>{file.name}</div>
                                            <div style={{
                                                fontSize: 11, color: BUG.textMuted, marginTop: 3,
                                                display: 'inline-flex', alignItems: 'center', gap: 6,
                                            }}>
                                                <span style={{
                                                    width: 6, height: 6, borderRadius: '50%',
                                                    background: BUG.success,
                                                }} />
                                                {(file.size / 1024).toFixed(0)} КБ · готово
                                            </div>
                                        </div>
                                        <button
                                            onClick={() => { setFile(null); setFilePreview(null); }}
                                            style={removeFileBtn}
                                            title="Убрать"
                                        >✕</button>
                                    </div>
                                )}
                            </div>

                            {submitError && (
                                <div style={{
                                    background: BUG.dangerBg,
                                    border: `1px solid ${BUG.danger}55`,
                                    borderRadius: 10,
                                    padding: '10px 14px',
                                    marginBottom: 14,
                                    color: BUG.danger, fontSize: 13, fontWeight: 600,
                                    display: 'inline-flex', alignItems: 'center', gap: 8,
                                    width: '100%', boxSizing: 'border-box',
                                    animation: 'bugFadeIn 200ms ease',
                                }}>
                                    <span style={{ fontSize: 16 }}>⚠️</span>
                                    {submitError}
                                </div>
                            )}

                            <div style={{
                                display: 'flex', gap: 10, justifyContent: 'flex-end',
                                marginTop: 6,
                            }}>
                                <button onClick={onClose} style={btnSecondary} disabled={submitting}>
                                    Отмена
                                </button>
                                <button
                                    onClick={submit}
                                    disabled={submitting}
                                    style={{
                                        ...btnPrimary,
                                        opacity: submitting ? 0.6 : 1,
                                        cursor: submitting ? 'not-allowed' : 'pointer',
                                    }}
                                >
                                    {submitting ? 'Отправка…' : '🚀 Отправить'}
                                </button>
                            </div>
                        </div>
                    </>
                )}
            </div>
        </div>
    );
};

const BugTypeCard = ({ option, selected, onClick }) => {
    const [hovered, setHovered] = useState(false);
    return (
        <button
            type="button"
            onClick={onClick}
            onMouseEnter={() => setHovered(true)}
            onMouseLeave={() => setHovered(false)}
            style={{
                padding: '12px 14px',
                background: selected
                    ? BUG.gradientBrand
                    : (hovered ? BUG.bgHover : BUG.bgInput),
                border: selected
                    ? '1px solid transparent'
                    : `1px solid ${hovered ? BUG.borderHover : BUG.border}`,
                borderRadius: 12,
                color: selected ? '#fff' : BUG.text,
                cursor: 'pointer',
                fontFamily: BUG.font,
                textAlign: 'left',
                transition: 'all 200ms ease',
                display: 'flex', flexDirection: 'column', gap: 2,
                boxShadow: selected
                    ? '0 8px 20px rgba(51,87,255,0.40)'
                    : 'none',
                transform: selected ? 'translateY(-2px)' : 'translateY(0)',
            }}
        >
            <div style={{
                fontSize: 13, fontWeight: 800, letterSpacing: -0.1,
            }}>
                {option.label}
            </div>
            <div style={{
                fontSize: 11, fontWeight: 600,
                color: selected ? 'rgba(255,255,255,0.78)' : BUG.textMuted,
            }}>
                {option.desc}
            </div>
        </button>
    );
};

const FocusableInput = ({ value, onChange, placeholder, maxLength }) => {
    const [focus, setFocus] = useState(false);
    return (
        <input
            value={value}
            onChange={(e) => onChange(e.target.value)}
            onFocus={() => setFocus(true)}
            onBlur={() => setFocus(false)}
            placeholder={placeholder}
            maxLength={maxLength}
            style={{
                ...inputStyle,
                border: `1.5px solid ${focus ? BUG.accent : BUG.border}`,
                boxShadow: focus ? `0 0 0 3px ${BUG.accentBg}` : 'none',
            }}
        />
    );
};

const FocusableTextarea = ({ value, onChange, placeholder, rows }) => {
    const [focus, setFocus] = useState(false);
    return (
        <textarea
            value={value}
            onChange={(e) => onChange(e.target.value)}
            onFocus={() => setFocus(true)}
            onBlur={() => setFocus(false)}
            placeholder={placeholder}
            rows={rows}
            style={{
                ...inputStyle,
                resize: 'vertical',
                lineHeight: 1.5,
                border: `1.5px solid ${focus ? BUG.accent : BUG.border}`,
                boxShadow: focus ? `0 0 0 3px ${BUG.accentBg}` : 'none',
            }}
        />
    );
};

const SuccessView = ({ onClose }) => (
    <div style={{
        textAlign: 'center', padding: '48px 32px',
        background:
            'radial-gradient(ellipse at top, rgba(34,217,122,0.18) 0%, transparent 60%)',
    }}>
        <div style={{
            width: 88, height: 88, margin: '0 auto 18px',
            borderRadius: '50%',
            background: 'linear-gradient(135deg, #22d97a 0%, #0f9d56 100%)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 44,
            boxShadow:
                '0 16px 40px rgba(34,217,122,0.45), '
                + '0 0 0 8px rgba(34,217,122,0.16)',
            animation: 'bugFadeInScale 380ms cubic-bezier(0.34, 1.56, 0.64, 1)',
        }}>✅</div>
        <div style={{
            fontSize: 22, fontWeight: 800, color: BUG.text, marginBottom: 8,
            letterSpacing: -0.3,
        }}>
            Спасибо!
        </div>
        <div style={{
            fontSize: 13, color: BUG.textMuted, marginBottom: 24,
            maxWidth: 340, margin: '0 auto 24px', lineHeight: 1.55,
        }}>
            Баг-репорт отправлен. Мы посмотрим его в админке Рублокса
            и постараемся починить как можно скорее.
        </div>
        <button onClick={onClose} style={btnPrimary}>
            Закрыть
        </button>
    </div>
);

// ============================================================
// === Стили / палитра ===
// ============================================================
const BUG = {
    bgPanel:    '#ffffff',
    bgInput:    '#fafbfd',
    bgHover:    '#f1f5f9',
    border:     '#e5e7eb',
    borderHover:'#cbd5e1',
    text:       '#0f172a',
    textMuted:  '#475569',
    textDim:    '#94a3b8',
    accent:     '#3357ff',
    accentBg:   '#e0e8ff',
    success:    '#10b981',
    danger:     '#ef4444',
    dangerBg:   '#fef2f2',
    gradientBrand: 'linear-gradient(135deg, #3357ff 0%, #1e2da5 100%)',
    font:       '"Roboto Condensed", system-ui, -apple-system, sans-serif',
};

const BUG_KEYFRAMES = `
@keyframes bugFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
@keyframes bugFadeInScale { from { opacity: 0; transform: scale(0.94); } to { opacity: 1; transform: scale(1); } }
@keyframes bugFloat {
    0%, 100% { transform: translateY(0) rotate(0deg); }
    50%      { transform: translateY(-4px) rotate(6deg); }
}
@keyframes bugPulseRing {
    0%, 100% { box-shadow: 0 8px 20px rgba(51, 87, 255, 0.40), 0 0 0 0 rgba(51, 87, 255, 0.45); }
    50%      { box-shadow: 0 8px 20px rgba(51, 87, 255, 0.40), 0 0 0 10px rgba(51, 87, 255, 0); }
}
`;

const modalBackdrop = {
    position: 'fixed', inset: 0, zIndex: 2200,
    background: 'rgba(15, 23, 42, 0.55)',
    backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    fontFamily: BUG.font,
    animation: 'bugFadeIn 200ms ease',
};

const modalCard = {
    background: BUG.bgPanel,
    border: `1px solid ${BUG.border}`,
    borderRadius: 22,
    width: '100%', maxWidth: 540,
    color: BUG.text,
    overflow: 'hidden',
    boxShadow: '0 24px 60px rgba(15, 23, 42, 0.32), 0 0 0 1px rgba(51, 87, 255, 0.06)',
    maxHeight: '92vh', overflowY: 'auto',
    animation: 'bugFadeInScale 240ms cubic-bezier(0.34, 1.56, 0.64, 1)',
};

const iconCloseBtn = {
    width: 34, height: 34,
    border: '1px solid rgba(255,255,255,0.25)',
    background: 'rgba(255,255,255,0.10)',
    color: '#fff', borderRadius: 10,
    fontSize: 22, fontWeight: 700, lineHeight: 1,
    cursor: 'pointer', fontFamily: BUG.font,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    transition: 'all 150ms ease',
    position: 'relative', zIndex: 1,
};

const removeFileBtn = {
    width: 28, height: 28,
    background: 'rgba(255,111,122,0.16)',
    border: '1px solid rgba(255,111,122,0.35)',
    color: '#ff6f7a',
    borderRadius: 8,
    fontSize: 13, fontWeight: 700,
    cursor: 'pointer',
    fontFamily: BUG.font,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    transition: 'all 150ms ease',
    flexShrink: 0,
};

const btnPrimary = {
    padding: '10px 20px',
    background: BUG.gradientBrand,
    border: '1px solid transparent',
    color: '#fff',
    borderRadius: 10,
    fontSize: 14, fontWeight: 800,
    cursor: 'pointer',
    fontFamily: BUG.font,
    boxShadow: '0 6px 16px rgba(51,87,255,0.35)',
    transition: 'all 150ms ease',
    minWidth: 130,
    letterSpacing: 0.2,
};

const btnSecondary = {
    padding: '10px 18px',
    background: BUG.bgInput,
    border: `1px solid ${BUG.border}`,
    color: BUG.text,
    borderRadius: 10,
    fontSize: 14, fontWeight: 700,
    cursor: 'pointer',
    fontFamily: BUG.font,
    transition: 'all 150ms ease',
};

const field = { marginBottom: 16 };

const fieldLabel = {
    fontSize: 11,
    color: BUG.textMuted,
    marginBottom: 8,
    textTransform: 'uppercase',
    letterSpacing: 0.8,
    fontWeight: 800,
};

const inputStyle = {
    width: '100%', boxSizing: 'border-box',
    background: BUG.bgInput,
    color: BUG.text,
    border: `1.5px solid ${BUG.border}`,
    borderRadius: 10,
    padding: '11px 14px',
    fontSize: 14,
    fontFamily: BUG.font,
    outline: 'none',
    transition: 'all 150ms ease',
};

export default KubikonBugReportButton;
