'use client';

import { useEffect, useState } from 'react';
import { ToolCheckResult } from '@/lib/tool-check';
import { RefreshCw, AlertTriangle, CheckCircle } from 'lucide-react';

export function ToolChecker({ children }: { children: React.ReactNode }) {
    const [result, setResult] = useState<ToolCheckResult | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [skipped, setSkipped] = useState(false);

    const checkTools = async () => {
        setLoading(true);
        setError(null);
        try {
            const res = await fetch('/api/system/check-tools');
            if (!res.ok) {
                throw new Error('Failed to check tools');
            }
            const data: ToolCheckResult = await res.json();
            setResult(data);
        } catch (err) {
            setError('Failed to communicate with the server.');
        } finally {
            setLoading(false);
        }
    };

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

    const handleSkip = () => {
        if (confirm("WARNING: Skipping these checks may cause the application to fail or produce corrupt files. Are you sure you want to proceed without the required tools?")) {
            setSkipped(true);
        }
    };

    if (loading) {
        return (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-background text-foreground">
                <div className="flex flex-col items-center gap-4">
                    <RefreshCw className="h-8 w-8 animate-spin text-primary" />
                    <p className="text-lg font-medium">Checking system prerequisites...</p>
                </div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-background text-foreground p-4">
                <div className="max-w-md w-full bg-card border border-border rounded-lg shadow-lg p-6 flex flex-col items-center text-center gap-4">
                    <div className="h-12 w-12 rounded-full bg-red-500/10 flex items-center justify-center">
                        <AlertTriangle className="h-6 w-6 text-red-400" />
                    </div>
                    <h2 className="text-xl font-bold">System Check Failed</h2>
                    <p className="text-muted-foreground">{error}</p>
                    <div className="flex flex-col gap-2 w-full">
                        <button
                            onClick={checkTools}
                            className="w-full px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors flex items-center justify-center gap-2"
                        >
                            <RefreshCw className="h-4 w-4" />
                            Retry
                        </button>
                        <button
                            onClick={handleSkip}
                            className="w-full px-4 py-2 text-sm text-yellow-500/80 hover:text-yellow-500 hover:bg-yellow-500/10 rounded-md transition-colors"
                        >
                            Skip Checks (Unsafe)
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    if (result && !result.allExists && !skipped) {
        return (
            <div className="fixed inset-0 z-50 flex items-center justify-center bg-background text-foreground p-4">
                <div className="max-w-md w-full bg-card border border-border rounded-lg shadow-lg p-6 flex flex-col gap-6">
                    <div className="flex flex-col items-center text-center gap-2">
                        <div className="h-12 w-12 rounded-full bg-red-500/10 flex items-center justify-center">
                            <AlertTriangle className="h-6 w-6 text-red-400" />
                        </div>
                        <h2 className="text-xl font-bold">System Check Failed</h2>
                        <p className="text-muted-foreground">
                            {result.mkbrrPresetExists === false
                                ? 'The required "red" preset for mkbrr is missing.'
                                : 'Some required CLI tools are missing from your system. Please install them to continue.'}
                        </p>
                    </div>

                    <div className="space-y-3">
                        {result.tools.map((tool) => (
                            <div
                                key={tool.name}
                                className={`flex items-center justify-between p-3 rounded-md border ${tool.exists
                                    ? 'bg-muted/50 border-border'
                                    : 'bg-red-400/5 border-red-400/20'
                                    }`}
                            >
                                <div className="flex items-center gap-3">
                                    <span className="font-mono text-sm font-medium">{tool.name}</span>
                                </div>
                                {tool.exists ? (
                                    <div className="flex items-center gap-2 text-green-500 text-sm">
                                        <CheckCircle className="h-4 w-4" />
                                        <span>Installed</span>
                                    </div>
                                ) : (
                                    <div className="flex items-center gap-2 text-red-400 text-sm">
                                        <AlertTriangle className="h-4 w-4" />
                                        <span>Missing</span>
                                    </div>
                                )}
                            </div>
                        ))}

                        {result.mkbrrPresetExists === false && (
                            <div className="p-3 rounded-md border bg-red-400/5 border-red-400/20">
                                <div className="flex flex-col gap-2">
                                    <div className="flex items-center justify-between">
                                        <span className="font-mono text-sm font-medium">mkbrr preset: red</span>
                                        <div className="flex items-center gap-2 text-red-400 text-sm">
                                            <AlertTriangle className="h-4 w-4" />
                                            <span>Missing</span>
                                        </div>
                                    </div>
                                    <p className="text-xs text-muted-foreground mt-1">
                                        Please create the preset by following the documentation.
                                    </p>
                                    <a
                                        href="https://mkbrr.com/features/presets"
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="text-xs text-primary hover:underline"
                                    >
                                        View Documentation
                                    </a>
                                </div>
                            </div>
                        )}
                    </div>

                    <div className="flex flex-col gap-2">
                        <button
                            onClick={checkTools}
                            className="w-full px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors flex items-center justify-center gap-2"
                        >
                            <RefreshCw className="h-4 w-4" />
                            Recheck Dependencies
                        </button>
                        <button
                            onClick={handleSkip}
                            className="w-full px-4 py-2 text-sm text-yellow-500/80 hover:text-yellow-500 hover:bg-yellow-500/10 rounded-md transition-colors"
                        >
                            Skip Checks (Unsafe)
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    return <>{children}</>;
}
