import React, { useEffect, useState, useRef } from 'react';
import { createShare, getAllShares, deleteShare } from '../services/shareService';

const EXPIRY_OPTIONS = [
    { label: 'Kein Ablauf', value: '' },
    { label: '1 Stunde', value: '1' },
    { label: '4 Stunden', value: '4' },
    { label: '24 Stunden', value: '24' },
    { label: '3 Tage', value: '72' },
    { label: '7 Tage', value: '168' },
    { label: '30 Tage', value: '720' },
];

const DOWNLOAD_OPTIONS = [
    { label: 'Unbegrenzt', value: '' },
    { label: '1×', value: '1' },
    { label: '5×', value: '5' },
    { label: '10×', value: '10' },
    { label: '25×', value: '25' },
];

const formatDate = (d) => d ? new Date(d + 'Z').toLocaleString('de-DE') : '—';
const isExpired = (s) => {
    if (s.expires_at && new Date(s.expires_at + 'Z') < new Date()) return true;
    if (s.max_downloads && s.download_count >= s.max_downloads) return true;
    return false;
};

export default function SharesPage() {
    const [shares, setShares] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showModal, setShowModal] = useState(false);
    const [copiedId, setCopiedId] = useState(null);
    const [form, setForm] = useState({
        type: 'text',
        text_content: '',
        password: '',
        expires_in_hours: '',
        max_downloads: '',
    });
    const [file, setFile] = useState(null);
    const [creating, setCreating] = useState(false);
    const [createError, setCreateError] = useState('');
    const [newLink, setNewLink] = useState('');
    const fileRef = useRef();

    const load = async () => {
        try {
            setLoading(true);
            setShares(await getAllShares());
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { load(); }, []);

    const handleCreate = async (e) => {
        e.preventDefault();
        setCreateError('');
        setCreating(true);
        try {
            const fd = new FormData();
            fd.append('type', form.type);
            if (form.type === 'text') fd.append('text_content', form.text_content);
            if (form.type === 'file' && file) fd.append('file', file);
            if (form.password) fd.append('password', form.password);
            if (form.expires_in_hours) fd.append('expires_in_hours', form.expires_in_hours);
            if (form.max_downloads) fd.append('max_downloads', form.max_downloads);

            const result = await createShare(fd);
            setNewLink(result.public_url);
            await load();
        } catch (e) {
            setCreateError(e.message);
        } finally {
            setCreating(false);
        }
    };

    const handleDelete = async (id) => {
        if (!window.confirm('Share wirklich löschen?')) return;
        await deleteShare(id);
        setShares(prev => prev.filter(s => s.id !== id));
    };

    const copyLink = (url, id) => {
        navigator.clipboard.writeText(url);
        setCopiedId(id);
        setTimeout(() => setCopiedId(null), 2000);
    };

    const resetModal = () => {
        setShowModal(false);
        setForm({ type: 'text', text_content: '', password: '', expires_in_hours: '', max_downloads: '' });
        setFile(null);
        setNewLink('');
        setCreateError('');
        if (fileRef.current) fileRef.current.value = '';
    };

    return (
        <div style={{ padding: '24px', maxWidth: 1000, margin: '0 auto' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
                <div>
                    <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700 }}>🔗 Sichere Links</h1>
                    <p style={{ margin: '4px 0 0', color: '#6B7280', fontSize: 14 }}>
                        Dateien und Texte sicher teilen — mit Ablauf und Passwortschutz
                    </p>
                </div>
                <button
                    onClick={() => setShowModal(true)}
                    style={{
                        background: '#3B82F6', color: '#fff', border: 'none',
                        borderRadius: 8, padding: '10px 18px', cursor: 'pointer', fontWeight: 600,
                    }}
                >
                    + Neuer Link
                </button>
            </div>

            {loading ? (
                <p style={{ color: '#6B7280' }}>Lädt…</p>
            ) : shares.length === 0 ? (
                <div style={{ textAlign: 'center', padding: 60, color: '#9CA3AF' }}>
                    <div style={{ fontSize: 48 }}>🔗</div>
                    <p>Noch keine Links erstellt.</p>
                </div>
            ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                    {shares.map(s => {
                        const expired = isExpired(s);
                        return (
                            <div key={s.id} style={{
                                background: 'var(--bg-secondary, #F9FAFB)',
                                border: '1px solid var(--border, #E5E7EB)',
                                borderRadius: 10,
                                padding: '14px 18px',
                                display: 'flex',
                                alignItems: 'center',
                                gap: 16,
                                opacity: expired ? 0.6 : 1,
                            }}>
                                <span style={{ fontSize: 24 }}>{s.type === 'file' ? '📄' : '📝'}</span>
                                <div style={{ flex: 1, minWidth: 0 }}>
                                    <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>
                                        {s.type === 'file' ? s.filename : 'Text-Share'}
                                        {expired && <span style={{ marginLeft: 8, fontSize: 11, color: '#EF4444', fontWeight: 700 }}>ABGELAUFEN</span>}
                                        {s.password_hash && <span style={{ marginLeft: 6, fontSize: 11, color: '#6B7280' }}>🔒</span>}
                                    </div>
                                    <div style={{ fontSize: 12, color: '#6B7280' }}>
                                        Erstellt: {formatDate(s.created_at)}
                                        {s.expires_at && ` · Läuft ab: ${formatDate(s.expires_at)}`}
                                        {s.max_downloads && ` · Downloads: ${s.download_count}/${s.max_downloads}`}
                                        {s.created_by_username && ` · Von: ${s.created_by_username}`}
                                    </div>
                                </div>
                                <div style={{ display: 'flex', gap: 8 }}>
                                    <button
                                        onClick={() => copyLink(s.public_url, s.id)}
                                        style={{
                                            background: copiedId === s.id ? '#10B981' : '#E5E7EB',
                                            color: copiedId === s.id ? '#fff' : '#374151',
                                            border: 'none', borderRadius: 6, padding: '6px 12px',
                                            cursor: 'pointer', fontSize: 13, fontWeight: 500,
                                        }}
                                    >
                                        {copiedId === s.id ? '✓ Kopiert' : '🔗 Link kopieren'}
                                    </button>
                                    <button
                                        onClick={() => handleDelete(s.id)}
                                        style={{
                                            background: '#FEE2E2', color: '#DC2626',
                                            border: 'none', borderRadius: 6, padding: '6px 10px',
                                            cursor: 'pointer', fontSize: 13,
                                        }}
                                    >
                                        🗑
                                    </button>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}

            {showModal && (
                <div style={{
                    position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    zIndex: 1000, padding: 20,
                }}>
                    <div style={{
                        background: 'var(--bg-primary, #fff)', borderRadius: 12,
                        padding: 28, width: '100%', maxWidth: 480,
                        maxHeight: '90vh', overflowY: 'auto',
                    }}>
                        {newLink ? (
                            <>
                                <h2 style={{ margin: '0 0 16px', fontSize: 18 }}>✅ Link erstellt</h2>
                                <p style={{ fontSize: 13, color: '#6B7280', marginBottom: 8 }}>
                                    Kopiere diesen Link und teile ihn mit der Zielperson:
                                </p>
                                <div style={{
                                    background: '#F3F4F6', borderRadius: 8, padding: '10px 14px',
                                    fontFamily: 'monospace', fontSize: 13, wordBreak: 'break-all',
                                    marginBottom: 16,
                                }}>
                                    {newLink}
                                </div>
                                <div style={{ display: 'flex', gap: 10 }}>
                                    <button
                                        onClick={() => { navigator.clipboard.writeText(newLink); }}
                                        style={{
                                            flex: 1, background: '#3B82F6', color: '#fff',
                                            border: 'none', borderRadius: 8, padding: '10px',
                                            cursor: 'pointer', fontWeight: 600,
                                        }}
                                    >
                                        🔗 Link kopieren
                                    </button>
                                    <button
                                        onClick={resetModal}
                                        style={{
                                            flex: 1, background: '#E5E7EB', color: '#374151',
                                            border: 'none', borderRadius: 8, padding: '10px',
                                            cursor: 'pointer', fontWeight: 600,
                                        }}
                                    >
                                        Schließen
                                    </button>
                                </div>
                            </>
                        ) : (
                            <form onSubmit={handleCreate}>
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
                                    <h2 style={{ margin: 0, fontSize: 18 }}>Neuer sicherer Link</h2>
                                    <button type="button" onClick={resetModal}
                                        style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#6B7280' }}>×</button>
                                </div>

                                {/* Typ */}
                                <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
                                    {['text', 'file'].map(t => (
                                        <button key={t} type="button"
                                            onClick={() => setForm(f => ({ ...f, type: t }))}
                                            style={{
                                                flex: 1, padding: '8px',
                                                borderRadius: 8, border: '2px solid',
                                                borderColor: form.type === t ? '#3B82F6' : '#E5E7EB',
                                                background: form.type === t ? '#EFF6FF' : 'transparent',
                                                color: form.type === t ? '#1D4ED8' : '#374151',
                                                cursor: 'pointer', fontWeight: 600, fontSize: 14,
                                            }}>
                                            {t === 'text' ? '📝 Text' : '📄 Datei'}
                                        </button>
                                    ))}
                                </div>

                                {/* Inhalt */}
                                {form.type === 'text' ? (
                                    <div style={{ marginBottom: 14 }}>
                                        <label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }}>Text / Inhalt *</label>
                                        <textarea
                                            value={form.text_content}
                                            onChange={e => setForm(f => ({ ...f, text_content: e.target.value }))}
                                            required rows={5}
                                            style={{
                                                width: '100%', borderRadius: 8, border: '1px solid #D1D5DB',
                                                padding: '8px 12px', fontSize: 14, resize: 'vertical',
                                                boxSizing: 'border-box', fontFamily: 'inherit',
                                            }}
                                            placeholder="Passwort, Zugangsdaten, Notiz…"
                                        />
                                    </div>
                                ) : (
                                    <div style={{ marginBottom: 14 }}>
                                        <label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }}>Datei *</label>
                                        <input ref={fileRef} type="file" required
                                            onChange={e => setFile(e.target.files[0])}
                                            style={{ width: '100%' }} />
                                        <div style={{ fontSize: 12, color: '#9CA3AF', marginTop: 4 }}>Max. 100 MB</div>
                                    </div>
                                )}

                                {/* Passwort */}
                                <div style={{ marginBottom: 14 }}>
                                    <label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }}>
                                        Passwortschutz <span style={{ color: '#9CA3AF', fontWeight: 400 }}>(optional)</span>
                                    </label>
                                    <input type="password" value={form.password}
                                        onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
                                        placeholder="Leer = kein Passwort"
                                        style={{
                                            width: '100%', borderRadius: 8, border: '1px solid #D1D5DB',
                                            padding: '8px 12px', fontSize: 14, boxSizing: 'border-box',
                                        }} />
                                </div>

                                {/* Ablauf + Downloads */}
                                <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
                                    <div style={{ flex: 1 }}>
                                        <label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }}>Ablauf</label>
                                        <select value={form.expires_in_hours}
                                            onChange={e => setForm(f => ({ ...f, expires_in_hours: e.target.value }))}
                                            style={{
                                                width: '100%', borderRadius: 8, border: '1px solid #D1D5DB',
                                                padding: '8px 12px', fontSize: 14, boxSizing: 'border-box',
                                            }}>
                                            {EXPIRY_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                                        </select>
                                    </div>
                                    <div style={{ flex: 1 }}>
                                        <label style={{ fontSize: 13, fontWeight: 600, display: 'block', marginBottom: 6 }}>Max. Downloads</label>
                                        <select value={form.max_downloads}
                                            onChange={e => setForm(f => ({ ...f, max_downloads: e.target.value }))}
                                            style={{
                                                width: '100%', borderRadius: 8, border: '1px solid #D1D5DB',
                                                padding: '8px 12px', fontSize: 14, boxSizing: 'border-box',
                                            }}>
                                            {DOWNLOAD_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                                        </select>
                                    </div>
                                </div>

                                {createError && (
                                    <div style={{ background: '#FEF2F2', color: '#DC2626', borderRadius: 8, padding: '10px 14px', marginBottom: 14, fontSize: 13 }}>
                                        {createError}
                                    </div>
                                )}

                                <div style={{ display: 'flex', gap: 10 }}>
                                    <button type="submit" disabled={creating}
                                        style={{
                                            flex: 1, background: creating ? '#93C5FD' : '#3B82F6',
                                            color: '#fff', border: 'none', borderRadius: 8,
                                            padding: '10px', cursor: creating ? 'not-allowed' : 'pointer',
                                            fontWeight: 600,
                                        }}>
                                        {creating ? 'Erstellt…' : '🔗 Link erstellen'}
                                    </button>
                                    <button type="button" onClick={resetModal}
                                        style={{
                                            background: '#E5E7EB', color: '#374151',
                                            border: 'none', borderRadius: 8, padding: '10px 16px',
                                            cursor: 'pointer', fontWeight: 600,
                                        }}>
                                        Abbrechen
                                    </button>
                                </div>
                            </form>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}
