"use client";

import { useEffect, useState } from "react";
import {
    Cloud,
    Settings,
    ExternalLink,
    CheckCircle2,
    AlertCircle,
    RefreshCw,
    XOctagon,
    Key,
    FolderOpen
} from "lucide-react";
import { getSettingGroup, updateSetting, getGDriveAuthUrl, testGDriveConnection, disconnectGDrive } from "@/lib/api";
import { useUI } from "@/context/UIContext";
import { clsx } from "clsx";

export default function GDriveSettings() {
    const { confirm, alert, toast } = useUI();
    const [data, setData] = useState<any>(null);
    const [saving, setSaving] = useState(false);
    const [testing, setTesting] = useState(false);
    const [testResult, setTestResult] = useState<any>(null);

    useEffect(() => {
        getSettingGroup('gdrive').then(setData);
    }, []);

    const handleSave = async () => {
        setSaving(true);
        try {
            await updateSetting('gdrive', data);
            toast("GDrive configuration saved!", "success");
        } catch (err: any) {
            alert({ title: "Save Failed", message: err.message, type: "error" });
        } finally {
            setSaving(false);
        }
    };

    const handleConnect = async () => {
        try {
            const { authUrl } = await getGDriveAuthUrl();
            const win = window.open(authUrl, '_blank', 'width=600,height=700');
            const timer = setInterval(() => {
                if (win?.closed) {
                    clearInterval(timer);
                    getSettingGroup('gdrive').then(setData);
                }
            }, 1000);
        } catch (err: any) {
            alert({ title: "Connection Error", message: err.message, type: "error" });
        }
    };

    const handleTest = async () => {
        setTesting(true);
        setTestResult(null);
        try {
            const res = await testGDriveConnection();
            setTestResult(res);
        } catch (err: any) {
            setTestResult({ error: err.message });
        } finally {
            setTesting(false);
        }
    };

    if (!data) return <div className="p-10 text-center animate-pulse text-white/20">Loading storage config...</div>;

    return (
        <div className="space-y-6 max-w-4xl">
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">Google <span className="text-white">Drive</span></h1>
                    <p className="text-white/40 text-sm mt-1">Configure automated uploads to GDrive clusters.</p>
                </div>
                <div className={clsx(
                    "px-4 py-2 rounded-xl flex items-center gap-3 border transition-all",
                    data.connected ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-400" : "bg-white/5 border-white/10 text-white/30"
                )}>
                    {data.connected ? <CheckCircle2 className="w-5 h-5 " /> : <AlertCircle className="w-5 h-5" />}
                    <span className="text-xs font-black uppercase tracking-widest">{data.connected ? 'Active Connection' : 'Not Connected'}</span>
                </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <div className="card p-8 space-y-6">
                    <div className="flex items-center gap-2 mb-2">
                        <Key className="w-4 h-4 text-white" />
                        <h3 className="section-title">API Credentials</h3>
                    </div>

                    <InputGroup
                        label="OAuth Client ID"
                        value={data.clientId}
                        onChange={(v: string) => setData({ ...data, clientId: v })}
                        placeholder="paste your google client id"
                    />
                    <InputGroup
                        label="OAuth Client Secret"
                        type="password"
                        value={data.clientSecret}
                        onChange={(v: string) => setData({ ...data, clientSecret: v })}
                        placeholder={data.clientSecretSet ? "••••••••••••••••" : "paste your secret"}
                    />
                    <InputGroup
                        label="Root Folder ID"
                        value={data.rootFolderId}
                        onChange={(v: string) => setData({ ...data, rootFolderId: v })}
                        placeholder="folder id from drive url"
                        help="Navigate to your target folder on Drive. The ID is the long string at the end of the URL."
                    />

                    <button onClick={handleSave} disabled={saving} className="btn-primary w-full justify-center">
                        {saving ? "Saving Config..." : "Save Configuration"}
                    </button>
                </div>

                <div className="space-y-6">
                    {/* Connection Panel */}
                    <div className="card p-8 bg-cyber-gradient border-accent-cyan/10">
                        <div className="flex items-center gap-2 mb-4">
                            <Cloud className="w-5 h-5 text-white" />
                            <h3 className="font-bold">Authorization Node</h3>
                        </div>
                        <p className="text-xs text-white/50 leading-relaxed mb-6">
                            Authorize the system to upload files to your account. This uses secure OAuth2 protocols. We only ask for file creation and read access in your drive.
                        </p>

                        <div className="flex flex-col gap-3">
                            <button onClick={handleConnect} disabled={!data.clientId} className="btn-violet h-12 justify-center ">
                                Connect Google Drive API
                            </button>

                            <div className="grid grid-cols-2 gap-3">
                                <button onClick={handleTest} disabled={!data.connected || testing} className="btn-ghost justify-center py-3">
                                    {testing ? <RefreshCw className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
                                    Test Node
                                </button>
                                <button
                                    onClick={async () => {
                                        const ok = await confirm({ title: "Disconnect Storage?", message: "Are you sure you want to disconnect GDrive? You will need to re-authorize later.", type: "danger", confirmLabel: "Disconnect" });
                                        if (ok) disconnectGDrive().then(() => {
                                            setData({ ...data, connected: false });
                                            toast("Google Drive disconnected", "info");
                                        });
                                    }}
                                    className="btn-ghost justify-center py-3 border-red-500/10 hover:border-red-500/20 text-red-400"
                                >
                                    <XOctagon className="w-4 h-4" />
                                    Reset
                                </button>
                            </div>
                        </div>
                    </div>

                    {testResult && (
                        <div className={clsx(
                            "p-4 rounded-2xl border animate-slide-up bg-opacity-10",
                            testResult.error ? "bg-red-500 border-red-500/20" : "bg-emerald-500 border-emerald-500/20"
                        )}>
                            <div className="flex items-start gap-4">
                                {testResult.error ? <AlertCircle className="w-5 h-5 text-red-400 mt-0.5" /> : <CheckCircle2 className="w-5 h-5 text-emerald-400 mt-0.5" />}
                                <div>
                                    <h4 className={clsx("text-sm font-bold uppercase tracking-widest", testResult.error ? "text-red-400" : "text-emerald-400")}>
                                        {testResult.error ? 'Node Error' : 'Node Ready'}
                                    </h4>
                                    <p className="text-xs text-white/60 mt-1">
                                        {testResult.error ? testResult.error : `Success. Authenticated as ${testResult.user.displayName} (${testResult.user.emailAddress}).`}
                                    </p>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            <div className="p-4 bg-white/[0.02] border border-white/5 rounded-2xl flex items-center gap-3">
                <FolderOpen className="w-5 h-5 text-white/30" />
                <p className="text-[10px] text-white/30 font-bold uppercase tracking-widest">
                    Hint: Ensure you have added <code className="text-white">http://localhost:3001/api/gdrive/oauth/callback</code> to your Google Cloud Redirect URIs.
                </p>
            </div>
        </div>
    );
}

function InputGroup({ label, value, onChange, placeholder, type = "text", help }: { label: string, value: string, onChange: (v: string) => void, placeholder: string, type?: string, help?: string }) {
    return (
        <div className="space-y-1.5">
            <label className="text-[10px] font-black uppercase tracking-widest text-white/30">{label}</label>
            <input
                type={type}
                value={value}
                onChange={(e) => onChange(e.target.value)}
                placeholder={placeholder}
                className="input"
            />
            {help && <p className="text-[10px] text-white/20 mt-1 italic leading-tight">{help}</p>}
        </div>
    );
}
