import React, { useState, useEffect } from 'react';
import { Head } from '@inertiajs/react';
import AdminLayout from '@/Admin/Layouts/AdminLayout'; 
import SettingsLayout from '@/Admin/Layouts/SettingsLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Loader2, Save, UserPlus, ShieldAlert } from 'lucide-react';
import axios from 'axios';
import { toast } from 'sonner';

export default function AuthSettings() {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [enabled, setEnabled] = useState(true);

    useEffect(() => {
        axios.get('/api/admin/settings/auth')
            .then(res => {
                setEnabled(res.data.registration_enabled);
            })
            .catch(error => {
                console.error(error);
                toast.error("Failed to load settings.");
            })
            .finally(() => setLoading(false));
    }, []);

    const handleSave = async () => {
        setSaving(true);
        try {
            const res = await axios.post('/api/admin/settings/auth', {
                registration_enabled: enabled
            });
            // Display success message (using backend message if available)
            toast.success(res.data.message || "Settings updated successfully.");
        } catch (error) {
            console.error(error);
            toast.error("Failed to update settings.");
        } finally {
            setSaving(false);
        }
    };

    return (
        <AdminLayout header="Settings">
            <Head title="Authentication Settings" />

            <SettingsLayout>
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <UserPlus className="w-5 h-5" /> Registration Control
                        </CardTitle>
                        <CardDescription>
                            Manage who can sign up for your application.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6 pt-4">
                        {loading ? (
                            <div className="flex justify-center py-8">
                                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                            </div>
                        ) : (
                            <>
                                <div className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm bg-card">
                                    <div className="space-y-0.5">
                                        <Label className="text-base">Enable Public Registration</Label>
                                        <p className="text-sm text-muted-foreground">
                                            If disabled, only Admins can create new users via the User Management page.
                                        </p>
                                    </div>
                                    <Switch 
                                        checked={enabled}
                                        onCheckedChange={setEnabled}
                                    />
                                </div>

                                {!enabled && (
                                    <div className="bg-yellow-50 dark:bg-yellow-900/20 text-yellow-800 dark:text-yellow-200 p-4 rounded-md flex items-start gap-3 text-sm border border-yellow-200 dark:border-yellow-800">
                                        <ShieldAlert className="w-5 h-5 shrink-0" />
                                        <p>
                                            <strong>Warning:</strong> Disabling registration will hide the "Sign Up" button on the homepage and login page. Users attempting to access the register route directly will see a 403 error.
                                        </p>
                                    </div>
                                )}

                                <div className="flex justify-end pt-4">
                                    <Button onClick={handleSave} disabled={saving} className="min-w-[150px]">
                                        {saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
                                        Save Changes
                                    </Button>
                                </div>
                            </>
                        )}
                    </CardContent>
                </Card>
            </SettingsLayout>
        </AdminLayout>
    );
}