import React, { useEffect, useRef, useState } from 'react';
import axios from '../../../bootstrap';
import { DownloadCloud, Loader2, Package, RefreshCw, Upload } from 'lucide-react';

function formatBytes(bytes: number): string {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function formatTimestamp(value: string | null | undefined): string {
    if (!value) return 'Unknown';
    return new Date(value).toLocaleString();
}

export function PluginReleasesView() {
    const [releases, setReleases] = useState<any[]>([]);
    const [latestVersion, setLatestVersion] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [isUploading, setIsUploading] = useState(false);
    const [isForcing, setIsForcing] = useState(false);
    const [message, setMessage] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);
    const fileInputRef = useRef<HTMLInputElement | null>(null);

    const fetchReleases = async () => {
        try {
            const response = await axios.get('/plugin-releases');
            setReleases(response.data.releases || []);
            setLatestVersion(response.data.latest_version || null);
        } catch (err) {
            console.error(err);
            setError('Could not load plugin releases.');
        } finally {
            setIsLoading(false);
        }
    };

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

    const handleUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) return;

        setIsUploading(true);
        setError(null);
        setMessage(null);

        const formData = new FormData();
        formData.append('package', file);

        try {
            const response = await axios.post('/plugin-releases', formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });
            setMessage(response.data.message || 'Plugin release uploaded.');
            await fetchReleases();
        } catch (err: any) {
            setError(err.response?.data?.message || 'Upload failed.');
        } finally {
            setIsUploading(false);
            if (fileInputRef.current) {
                fileInputRef.current.value = '';
            }
        }
    };

    const handleForceUpdateAll = async () => {
        if (!latestVersion) {
            setError('Upload a plugin release package first.');
            return;
        }

        if (!window.confirm(`Force update all connected websites to version ${latestVersion}?`)) {
            return;
        }

        setIsForcing(true);
        setError(null);
        setMessage(null);

        try {
            const response = await axios.post('/plugin-releases/force-update', {
                version: latestVersion,
            });
            setMessage(`${response.data.message} (${response.data.queued} websites queued)`);
        } catch (err: any) {
            setError(err.response?.data?.message || 'Force update failed.');
        } finally {
            setIsForcing(false);
        }
    };

    return (
        <div className="space-y-6 animate-fade-in">
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                    <h1 className="text-2xl font-bold text-white">Plugin Releases</h1>
                    <p className="text-sm text-slate-400 mt-1">
                        Upload a new A-Monster Guard plugin package and push it to all connected websites.
                    </p>
                </div>
                <div className="flex flex-wrap gap-3">
                    <button
                        type="button"
                        onClick={() => fileInputRef.current?.click()}
                        disabled={isUploading}
                        className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-indigo-500 hover:bg-indigo-400 text-white text-sm font-semibold transition disabled:opacity-60"
                    >
                        {isUploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}
                        Upload Release
                    </button>
                    <button
                        type="button"
                        onClick={handleForceUpdateAll}
                        disabled={isForcing || !latestVersion}
                        className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl border border-rose-500/30 bg-rose-500/10 text-rose-300 hover:bg-rose-500/20 text-sm font-semibold transition disabled:opacity-60"
                    >
                        {isForcing ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
                        Force Update All Sites
                    </button>
                    <input
                        ref={fileInputRef}
                        type="file"
                        accept=".zip"
                        className="hidden"
                        onChange={handleUpload}
                    />
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="rounded-2xl border border-slate-800 bg-slate-900/60 p-5">
                    <p className="text-[10px] uppercase tracking-widest text-slate-500 font-bold">Latest Version</p>
                    <p className="text-2xl font-black text-emerald-400 mt-2">{latestVersion || 'None'}</p>
                </div>
                <div className="rounded-2xl border border-slate-800 bg-slate-900/60 p-5">
                    <p className="text-[10px] uppercase tracking-widest text-slate-500 font-bold">Stored Packages</p>
                    <p className="text-2xl font-black text-white mt-2">{releases.length}</p>
                </div>
                <div className="rounded-2xl border border-slate-800 bg-slate-900/60 p-5">
                    <p className="text-[10px] uppercase tracking-widest text-slate-500 font-bold">Delivery</p>
                    <p className="text-sm text-slate-300 mt-2">Queued on next heartbeat (usually within 5 minutes).</p>
                </div>
            </div>

            {message && (
                <div className="rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-300">
                    {message}
                </div>
            )}

            {error && (
                <div className="rounded-xl border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-sm text-rose-300">
                    {error}
                </div>
            )}

            <div className="rounded-2xl border border-slate-800 bg-slate-900/40 overflow-hidden">
                <div className="px-5 py-4 border-b border-slate-800 flex items-center gap-2">
                    <Package className="w-4 h-4 text-indigo-400" />
                    <h2 className="text-sm font-bold text-white uppercase tracking-wide">Release Packages</h2>
                </div>

                {isLoading ? (
                    <div className="p-8 text-center text-slate-500 text-sm">Loading releases...</div>
                ) : releases.length === 0 ? (
                    <div className="p-8 text-center text-slate-500 text-sm">
                        No release uploaded yet. Run <code className="text-slate-300">php artisan plugin:build-release</code> then upload the zip from <code className="text-slate-300">storage/app/releases/</code>.
                    </div>
                ) : (
                    <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                            <thead className="text-[10px] uppercase tracking-widest text-slate-500 bg-slate-950/40">
                                <tr>
                                    <th className="py-3 px-4 text-left">Filename</th>
                                    <th className="py-3 px-4 text-left">Version</th>
                                    <th className="py-3 px-4 text-left">Size</th>
                                    <th className="py-3 px-4 text-left">Uploaded</th>
                                </tr>
                            </thead>
                            <tbody>
                                {releases.map((release) => (
                                    <tr key={release.filename} className="border-t border-slate-800/80">
                                        <td className="py-3 px-4 font-mono text-slate-300">{release.filename}</td>
                                        <td className="py-3 px-4 text-emerald-400 font-semibold">{release.version || 'Unversioned'}</td>
                                        <td className="py-3 px-4 text-slate-400">{formatBytes(release.size_bytes)}</td>
                                        <td className="py-3 px-4 text-slate-400">{formatTimestamp(release.uploaded_at)}</td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                )}
            </div>

            <div className="rounded-2xl border border-slate-800 bg-slate-950/40 p-5 text-sm text-slate-400 space-y-2">
                <p className="font-semibold text-slate-300 flex items-center gap-2">
                    <DownloadCloud className="w-4 h-4 text-indigo-400" />
                    How it works
                </p>
                <p>1. Bump <code className="text-slate-200">Version</code> and <code className="text-slate-200">AMG_AGENT_VERSION</code> in <code className="text-slate-200">a-monster-guard-agent.php</code>.</p>
                <p>2. Build a production zip locally (excludes <code className="text-slate-200">tests/</code>):</p>
                <p className="font-mono text-xs text-indigo-300 bg-slate-900/80 rounded-lg px-3 py-2">php artisan plugin:build-release</p>
                <p>3. Upload the generated file from <code className="text-slate-200">storage/app/releases/</code> (e.g. <code className="text-slate-200">a-monster-guard-1.2.0.zip</code>).</p>
                <p>4. Click <strong className="text-slate-200">Force Update All Sites</strong> to queue the update command on every active website.</p>
                <p>5. Each site downloads the package from the Control Center during its next heartbeat and installs it automatically.</p>
            </div>
        </div>
    );
}
