import React, { useState, useRef } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Button } from "primereact/button";
import { ProgressSpinner } from "primereact/progressspinner";
import { Toast } from "primereact/toast";
import axios from "axios";

export default function SystemUpdate({ auth, updateHistory = [], currentVersion: initialVersion = "2.1.0" }) {
    const toast = useRef(null);
    const [checking, setChecking] = useState(false);
    const [updateAvailable, setUpdateAvailable] = useState(false);
    const [currentVersion, setCurrentVersion] = useState(initialVersion);
    const [latestVersion, setLatestVersion] = useState(initialVersion);
    const [lastChecked, setLastChecked] = useState(new Date().toLocaleDateString());

    const [updateData, setUpdateData] = useState(null);
    const [downloading, setDownloading] = useState(false);
    const [downloadProgress, setDownloadProgress] = useState(null);
    const [installing, setInstalling] = useState(false);
    const [installed, setInstalled] = useState(false);
    const [history, setHistory] = useState(updateHistory || []);

    const handleCheckUpdate = async () => {
        setChecking(true);
        try {
            const response = await axios.get(route("system-update.check"));
            const data = response.data;
            
            setCurrentVersion(data.current_version);
            setLatestVersion(data.latest_version);
            setUpdateAvailable(data.update_available);
            if (data.last_checked) {
                try {
                    const date = new Date(data.last_checked);
                    setLastChecked(isNaN(date.getTime()) ? new Date().toLocaleDateString() : date.toLocaleDateString());
                } catch (e) {
                    setLastChecked(new Date().toLocaleDateString());
                }
            } else {
                setLastChecked(new Date().toLocaleDateString());
            }
            
            if (data.update_data) {
                setUpdateData(data.update_data);
            } else {
                setUpdateData(null);
            }

            toast.current?.show({
                severity: data.update_available ? "info" : "success",
                summary: data.update_available ? "Update Available" : "Up to Date",
                detail: data.update_available 
                    ? `New version ${data.latest_version} is available`
                    : "You are running the latest version",
                life: 3000,
            });
        } catch (error) {
            console.error("Error checking for updates:", error);
            toast.current?.show({
                severity: "error",
                summary: "Error",
                detail: error.response?.data?.error || "Failed to check for updates. Please try again.",
                life: 3000,
            });
        } finally {
            setChecking(false);
        }
    };

    const getCategoryColor = (category) => {
        switch (category) {
            case "New Feature":
                return "bg-blue-100 text-blue-800";
            case "Enhancement":
                return "bg-green-100 text-green-800";
            case "Improvement":
                return "bg-purple-100 text-purple-800";
            default:
                return "bg-gray-100 text-gray-800";
        }
    };

    // Helper to get icon for feature category
    const getFeatureIcon = (category) => {
        switch (category) {
            case "New Feature":
                return "pi pi-star";
            case "Enhancement":
                return "pi pi-check-circle";
            case "Improvement":
                return "pi pi-bolt";
            default:
                return "pi pi-info-circle";
        }
    };

    // Helper to safely format dates
    const formatDate = (dateString, options = {}) => {
        if (!dateString) return "N/A";
        try {
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return "Invalid Date";
            const defaultOptions = {
                year: "numeric",
                month: "short",
                day: "numeric",
            };
            return date.toLocaleDateString("en-US", { ...defaultOptions, ...options });
        } catch (e) {
            return "Invalid Date";
        }
    };

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={
                <>
                    <h2 className="text-skin-header font-medium">System Update</h2>
                    <p className="text-skin-sub-header font-semibold text-xs">
                        Home - System Update
                    </p>
                </>
            }
        >
            <Toast ref={toast} />
            <div className="space-y-4 max-w-4xl">
                {/* Update Status */}
                <div className="bg-white rounded-lg border border-gray-200 p-6">
                    <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                        <div>
                            <h3 className="text-lg font-medium text-gray-900 mb-3">
                                System Version
                            </h3>
                            <div className="space-y-2 text-sm">
                                <div className="flex items-center gap-2">
                                    <span className="text-gray-500">Current:</span>
                                    <span className="font-medium text-gray-900">{currentVersion}</span>
                                </div>
                                {updateAvailable && (
                                    <div className="flex items-center gap-2">
                                        <span className="text-gray-500">Latest:</span>
                                        <span className="font-medium text-green-600">{latestVersion}</span>
                                        <span className="px-2 py-0.5 bg-green-100 text-green-700 text-xs rounded">
                                            Available
                                        </span>
                                    </div>
                                )}
                                <div className="text-xs text-gray-400 mt-3">
                                    Last checked: {lastChecked}
                                </div>
                            </div>
                        </div>
                        <Button
                            label="Check for Updates"
                            icon={checking ? undefined : "pi pi-refresh"}
                            onClick={handleCheckUpdate}
                            disabled={checking}
                            className="p-button-outlined"
                            size="small"
                        >
                            {checking && (
                                <ProgressSpinner
                                    style={{ width: "16px", height: "16px" }}
                                    strokeWidth="4"
                                />
                            )}
                        </Button>
                    </div>
                </div>

                {updateAvailable ? (
                    <>
                        {/* Update Information */}
                        {updateData && (
                            <div className="bg-white rounded-lg border border-gray-200 p-6">
                                <div className="mb-4">
                                    <h3 className="text-lg font-medium text-gray-900 mb-2">
                                        Version {updateData.version}
                                    </h3>
                                    <p className="text-sm text-gray-500">
                                        Released on{" "}
                                        {formatDate(updateData.released_at, {
                                            month: "long",
                                        })}
                                    </p>
                                    {updateData.php_required && (
                                        <p className="text-xs text-gray-400 mt-1">
                                            PHP Required: {updateData.php_required}
                                        </p>
                                    )}
                                </div>
                            </div>
                        )}

                        {/* Changelog Section */}
                        {updateData && updateData.changelog && updateData.changelog.length > 0 && (
                            <div className="bg-white rounded-lg border border-gray-200 p-6">
                                <h3 className="text-lg font-medium text-gray-900 mb-4">
                                    Changelog
                                </h3>
                                <div className="space-y-2">
                                    {updateData.changelog.map((item, index) => (
                                        <div key={index} className="flex items-start gap-2 text-sm">
                                            <i className="pi pi-check-circle text-green-500 mt-0.5 text-xs"></i>
                                            <span className="text-gray-700">{item}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {/* Update Action */}
                        {updateData && (
                            <div className="bg-white rounded-lg border border-gray-200 p-6">
                                <div className="flex flex-col md:flex-row justify-between items-center gap-4">
                                    <div>
                                        <h3 className="text-base font-medium text-gray-900 mb-1">
                                            Download & Install Update
                                        </h3>
                                        <p className="text-xs text-gray-500">
                                            Make sure to backup your data before updating
                                        </p>
                                        {downloadProgress && (
                                            <div className="mt-2">
                                                <p className="text-xs text-green-600 font-medium">
                                                    {downloadProgress.message}
                                                </p>
                                                {downloadProgress.file_size_mb && (
                                                    <p className="text-xs text-gray-500">
                                                        File size: {downloadProgress.file_size_mb} MB
                                                    </p>
                                                )}
                                            </div>
                                        )}
                                        {installed && (
                                            <div className="mt-2">
                                                <p className="text-xs text-green-600 font-medium">
                                                    ✓ Update installed successfully! Please refresh the page.
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                    <div className="flex gap-2">
                                        {!downloadProgress && !installed && (
                                            <Button
                                                label={downloading ? "Downloading..." : "Download Update"}
                                                icon={downloading ? undefined : "pi pi-download"}
                                                className="p-button-success"
                                                disabled={downloading || installing}
                                                onClick={async () => {
                                                    if (!updateData.download_url) {
                                                        toast.current?.show({
                                                            severity: "warn",
                                                            summary: "Warning",
                                                            detail: "Download URL not available",
                                                            life: 3000,
                                                        });
                                                        return;
                                                    }

                                                    setDownloading(true);
                                                    setDownloadProgress(null);
                                                    
                                                    try {
                                                        const response = await axios.post(route("system-update.download"));
                                                        const data = response.data;
                                                        
                                                        if (data.success) {
                                                            setDownloadProgress({
                                                                message: data.message,
                                                                filename: data.filename,
                                                                file_size_mb: data.file_size_mb,
                                                                version: data.version,
                                                            });
                                                            
                                                            toast.current?.show({
                                                                severity: "success",
                                                                summary: "Success",
                                                                detail: `${data.message} - ${data.filename} (${data.file_size_mb} MB)`,
                                                                life: 5000,
                                                            });
                                                        } else {
                                                            toast.current?.show({
                                                                severity: "error",
                                                                summary: "Error",
                                                                detail: data.message || "Failed to download update",
                                                                life: 3000,
                                                            });
                                                        }
                                                    } catch (error) {
                                                        console.error("Error downloading update:", error);
                                                        toast.current?.show({
                                                            severity: "error",
                                                            summary: "Error",
                                                            detail: error.response?.data?.message || "Failed to download update. Please try again.",
                                                            life: 3000,
                                                        });
                                                    } finally {
                                                        setDownloading(false);
                                                    }
                                                }}
                                            >
                                                {downloading && (
                                                    <ProgressSpinner
                                                        style={{ width: "16px", height: "16px" }}
                                                        strokeWidth="4"
                                                    />
                                                )}
                                            </Button>
                                        )}
                                        
                                        {downloadProgress && !installed && (
                                            <Button
                                                label={installing ? "Installing..." : "Install Update"}
                                                icon={installing ? undefined : "pi pi-cog"}
                                                className="p-button-primary"
                                                disabled={installing || downloading}
                                                onClick={async () => {
                                                    if (!downloadProgress.version) {
                                                        toast.current?.show({
                                                            severity: "warn",
                                                            summary: "Warning",
                                                            detail: "Version information not available",
                                                            life: 3000,
                                                        });
                                                        return;
                                                    }

                                                    setInstalling(true);
                                                    
                                                    try {
                                                        const response = await axios.post(route("system-update.install"), {
                                                            version: downloadProgress.version,
                                                        });
                                                        const data = response.data;
                                                        
                                                        if (data.success) {
                                                            setInstalled(true);
                                                            setCurrentVersion(data.version);
                                                            
                                                       
                                                            
                                                            toast.current?.show({
                                                                severity: "success",
                                                                summary: "Success",
                                                                detail: `${data.message}. ${data.files_updated} files updated.`,
                                                                life: 5000,
                                                            });
                                                                 // Refresh page to get updated history
                                                        //  window.location.reload();
                                                            
                                                            // Show warning if there were any errors
                                                            if (data.warnings && data.warnings.length > 0) {
                                                                toast.current?.show({
                                                                    severity: "warn",
                                                                    summary: "Installation Warnings",
                                                                    detail: `Some files had issues: ${data.warnings.length} warnings`,
                                                                    life: 7000,
                                                                });
                                                            }
                                                        } else {
                                                            toast.current?.show({
                                                                severity: "error",
                                                                summary: "Error",
                                                                detail: data.message || "Failed to install update",
                                                                life: 3000,
                                                            });
                                                        }
                                                    } catch (error) {
                                                        console.error("Error installing update:", error);
                                                        toast.current?.show({
                                                            severity: "error",
                                                            summary: "Error",
                                                            detail: error.response?.data?.message || "Failed to install update. Please try again.",
                                                            life: 3000,
                                                        });
                                                    } finally {
                                                        setInstalling(false);
                                                    }
                                                }}
                                            >
                                                {installing && (
                                                    <ProgressSpinner
                                                        style={{ width: "16px", height: "16px" }}
                                                        strokeWidth="4"
                                                    />
                                                )}
                                            </Button>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}
                    </>
                ) : (
                    <div className="bg-white rounded-lg border border-gray-200 p-8 text-center">
                        <i className="pi pi-check-circle text-4xl text-green-500 mb-3"></i>
                        <h3 className="text-lg font-medium text-gray-900 mb-2">
                            System is Up to Date
                        </h3>
                        <p className="text-sm text-gray-500">
                            You are running version {currentVersion}
                        </p>
                    </div>
                )}

                {/* Update History Section */}
                <div className="bg-white rounded-lg border border-gray-200 p-6">
                    <h3 className="text-lg font-medium text-gray-900 mb-4">Installation History</h3>
                    {history && history.length > 0 ? (
                        <div className="space-y-3">
                            {history.map((update) => (
                                <div
                                    key={update.id}
                                    className="flex items-start justify-between pb-3 border-b border-gray-100 last:border-0 last:pb-0"
                                >
                                    <div className="flex-1">
                                        <div className="flex items-center gap-2 mb-1">
                                            <span className="text-sm font-medium text-gray-900">
                                                Version {update.version}
                                            </span>
                                            {update.is_latest && (
                                                <span className="px-2 py-0.5 bg-green-100 text-green-700 text-xs rounded">
                                                    Latest
                                                </span>
                                            )}
                                            {!update.is_active && (
                                                <span className="px-2 py-0.5 bg-gray-100 text-gray-700 text-xs rounded">
                                                    Inactive
                                                </span>
                                            )}
                                        </div>
                                        {update.description && (
                                            <p className="text-xs text-gray-500 mt-0.5">
                                                {update.description}
                                            </p>
                                        )}
                                        {update.installed_by && (
                                            <p className="text-xs text-gray-400 mt-1">
                                                Installed by: {update.installed_by}
                                            </p>
                                        )}
                                        {update.changelog && update.changelog.length > 0 && (
                                            <div className="mt-2 space-y-1">
                                                {update.changelog.slice(0, 2).map((item, index) => (
                                                    <p key={index} className="text-xs text-gray-500 flex items-start gap-1">
                                                        <i className="pi pi-check-circle text-green-500 text-xs mt-0.5"></i>
                                                        <span>{item}</span>
                                                    </p>
                                                ))}
                                                {update.changelog.length > 2 && (
                                                    <p className="text-xs text-gray-400">
                                                        +{update.changelog.length - 2} more changes
                                                    </p>
                                                )}
                                            </div>
                                        )}
                                    </div>
                                    <div className="text-right ml-4">
                                        {update.installed_at && (
                                            <span className="text-xs text-gray-400 block">
                                                {formatDate(update.installed_at)}
                                            </span>
                                        )}
                                        {update.release_date && (
                                            <span className="text-xs text-gray-400 block mt-1">
                                                Released: {formatDate(update.release_date)}
                                            </span>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div className="text-center py-8">
                            <i className="pi pi-history text-3xl text-gray-300 mb-3"></i>
                            <p className="text-sm text-gray-500">No installation history found</p>
                            <p className="text-xs text-gray-400 mt-1">
                                Updates you install will appear here
                            </p>
                        </div>
                    )}
                </div>
            </div>
        </AuthenticatedLayout>
    );
}

