import React, { createContext, useContext } from "react";
import { Outlet } from "react-router-dom";
import { useSettings, type FormValues, type ConfigMeta } from "@/hooks/use-settings";
import { Form } from "@/components/ui/form";
import { SectionHeader } from "@/components/section-header";
import { Button } from "@/components/ui/button";
import { Save, Loader2 } from "lucide-react";

interface SettingsContextType {
    form: ReturnType<typeof useSettings>["form"];
    meta: ConfigMeta | null;
}

const SettingsContext = createContext<SettingsContextType | null>(null);

export const useSettingsForm = () => {
    const context = useContext(SettingsContext);
    if (!context) throw new Error("useSettingsForm must be used within SettingsLayout");
    return context;
};

export function SettingsLayout() {
    const { form, meta, loading, isSaving, saveSettings } = useSettings();

    if (loading) {
        return (
            <div className="flex-1 flex items-center justify-center flex-col gap-4 min-h-[400px]">
                <Loader2 className="w-10 h-10 animate-spin text-primary" />
                <p className="text-muted-foreground animate-pulse">Loading configuration...</p>
            </div>
        );
    }

    return (
        <SettingsContext.Provider value={{ form, meta }}>
            <main className="pt-8 px-8 pb-12 max-w-7xl mx-auto space-y-8">
            <div className="flex justify-between items-end">
                <SectionHeader
                    badge="System"
                    title="Configuration"
                    description="Manage bot behavior, economy, and game systems."
                />
                <Button 
                    onClick={form.handleSubmit(saveSettings)} 
                    disabled={isSaving || !form.formState.isDirty}
                    className="shadow-lg hover:shadow-primary/20 transition-all font-bold min-w-[140px]"
                >
                    {isSaving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Save className="w-4 h-4 mr-2" />}
                    Save Changes
                </Button>
            </div>

            <div className="glass-card rounded-2xl border border-border/50 overflow-hidden">
                <Form {...form}>
                    <form className="flex flex-col h-full">
                        <div className="p-8">
                            <Outlet />
                        </div>
                    </form>
                </Form>
            </div>
            </main>
        </SettingsContext.Provider>
    );
}
