import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { getPublicShare, accessShare, getFileDownloadUrl } from '../services/shareService';

export default function PublicSharePage() {
    const { token } = useParams();
    const [share, setShare] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [password, setPassword] = useState('');
    const [unlocked, setUnlocked] = useState(false);
    const [textContent, setTextContent] = useState('');
    const [accessError, setAccessError] = useState('');
    const [copied, setCopied] = useState(false);
    const [checking, setChecking] = useState(false);

    useEffect(() => {
        getPublicShare(token)
            .then(data => {
                setShare(data);
                if (!data.has_password && data.type === 'text') {
                    setTextContent(data.text_content || '');
                    setUnlocked(true);
                } else if (!data.has_password && data.type === 'file') {
                    setUnlocked(true);
                }
            })
            .catch(e => setError(e.message))
            .finally(() => setLoading(false));
    }, [token]);

    const handleAccess = async (e) => {
        e.preventDefault();
        setAccessError('');
        setChecking(true);
        try {
            const result = await accessShare(token, password);
            if (result.text_content !== undefined) setTextContent(result.text_content);
            setUnlocked(true);
        } catch (e) {
            setAccessError(e.message);
        } finally {
            setChecking(false);
        }
    };

    const copyText = () => {
        navigator.clipboard.writeText(textContent);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    };

    const containerStyle = {
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 20,
        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
    };

    const cardStyle = {
        background: '#fff',
        borderRadius: 16,
        padding: 32,
        width: '100%',
        maxWidth: 520,
        boxShadow: '0 20px 60px rgba(0,0,0,0.2)',
    };

    if (loading) return (
        <div style={containerStyle}>
            <div style={cardStyle}>
                <p style={{ textAlign: 'center', color: '#6B7280' }}>Link wird geladen…</p>
            </div>
        </div>
    );

    if (error) return (
        <div style={containerStyle}>
            <div style={cardStyle}>
                <div style={{ textAlign: 'center' }}>
                    <div style={{ fontSize: 48, marginBottom: 16 }}>⚠️</div>
                    <h2 style={{ color: '#DC2626', margin: '0 0 8px' }}>Link nicht verfügbar</h2>
                    <p style={{ color: '#6B7280', margin: 0 }}>{error}</p>
                </div>
            </div>
        </div>
    );

    return (
        <div style={containerStyle}>
            <div style={cardStyle}>
                {/* Header */}
                <div style={{ textAlign: 'center', marginBottom: 24 }}>
                    <div style={{ fontSize: 40, marginBottom: 8 }}>
                        {share.type === 'file' ? '📄' : '📝'}
                    </div>
                    <h1 style={{ margin: '0 0 4px', fontSize: 22, color: '#111827' }}>
                        {share.type === 'file' ? share.filename : 'Sichere Nachricht'}
                    </h1>
                    <p style={{ margin: 0, fontSize: 13, color: '#9CA3AF' }}>
                        Sicherer IT Nexus Share
                        {share.expires_at && ` · Läuft ab: ${new Date(share.expires_at + 'Z').toLocaleString('de-DE')}`}
                    </p>
                </div>

                {!unlocked ? (
                    /* Passwort-Eingabe */
                    <form onSubmit={handleAccess}>
                        <div style={{ marginBottom: 16 }}>
                            <label style={{ display: 'block', fontWeight: 600, fontSize: 14, marginBottom: 8, color: '#374151' }}>
                                🔒 Passwort erforderlich
                            </label>
                            <input
                                type="password"
                                value={password}
                                onChange={e => setPassword(e.target.value)}
                                placeholder="Passwort eingeben…"
                                autoFocus
                                style={{
                                    width: '100%', borderRadius: 10, border: '2px solid #E5E7EB',
                                    padding: '12px 14px', fontSize: 15, boxSizing: 'border-box',
                                    outline: 'none',
                                }}
                                onFocus={e => e.target.style.borderColor = '#6366F1'}
                                onBlur={e => e.target.style.borderColor = '#E5E7EB'}
                            />
                        </div>
                        {accessError && (
                            <div style={{
                                background: '#FEF2F2', color: '#DC2626', borderRadius: 8,
                                padding: '10px 14px', marginBottom: 14, fontSize: 13, textAlign: 'center',
                            }}>
                                {accessError}
                            </div>
                        )}
                        <button type="submit" disabled={checking || !password}
                            style={{
                                width: '100%', background: checking ? '#A5B4FC' : '#6366F1',
                                color: '#fff', border: 'none', borderRadius: 10,
                                padding: '12px', fontSize: 15, fontWeight: 700,
                                cursor: checking || !password ? 'not-allowed' : 'pointer',
                            }}>
                            {checking ? 'Prüfen…' : 'Entsperren'}
                        </button>
                    </form>
                ) : share.type === 'text' ? (
                    /* Text anzeigen */
                    <div>
                        <div style={{
                            background: '#F8FAFC', border: '1px solid #E2E8F0',
                            borderRadius: 10, padding: 16, marginBottom: 16,
                            whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                            fontSize: 14, lineHeight: 1.6, maxHeight: 300, overflowY: 'auto',
                            fontFamily: 'ui-monospace, monospace',
                        }}>
                            {textContent}
                        </div>
                        <button onClick={copyText} style={{
                            width: '100%', background: copied ? '#10B981' : '#6366F1',
                            color: '#fff', border: 'none', borderRadius: 10,
                            padding: '12px', fontSize: 15, fontWeight: 700, cursor: 'pointer',
                            transition: 'background 0.2s',
                        }}>
                            {copied ? '✓ Kopiert!' : '📋 Inhalt kopieren'}
                        </button>
                    </div>
                ) : (
                    /* Datei-Download */
                    <div style={{ textAlign: 'center' }}>
                        <p style={{ color: '#4B5563', marginBottom: 20, fontSize: 14 }}>
                            Deine Datei ist bereit zum Download.
                            {share.max_downloads && (
                                <><br /><span style={{ color: '#6B7280' }}>
                                    Downloads: {share.download_count}/{share.max_downloads}
                                </span></>
                            )}
                        </p>
                        <a
                            href={getFileDownloadUrl(token, share.has_password ? password : undefined)}
                            download={share.filename}
                            style={{
                                display: 'inline-block', background: '#6366F1', color: '#fff',
                                borderRadius: 10, padding: '12px 32px', fontSize: 15,
                                fontWeight: 700, textDecoration: 'none',
                            }}
                        >
                            ⬇ {share.filename} herunterladen
                        </a>
                    </div>
                )}

                <p style={{ textAlign: 'center', marginTop: 24, marginBottom: 0, fontSize: 12, color: '#D1D5DB' }}>
                    Bereitgestellt via IT Nexus · Cereda Systems GmbH
                </p>
            </div>
        </div>
    );
}
