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 { Label } from "@/Components/ui/label";
import { Textarea } from "@/Components/ui/textarea";
import { Loader2, Save, Code, AlertTriangle } from 'lucide-react';
import axios from 'axios';
import { toast } from 'sonner';

export default function CodeInjection() {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    
    const [data, setData] = useState({
        header_code: '',
        footer_code: '',
    });

    useEffect(() => {
        axios.get('/api/admin/settings/code-injection')
            .then(res => {
                setData({
                    header_code: res.data.header_code || '',
                    footer_code: res.data.footer_code || '',
                });
            })
            .catch(() => toast.error("Failed to load settings."))
            .finally(() => setLoading(false));
    }, []);

    const handleSave = async () => {
        setSaving(true);
        try {
            await axios.post('/api/admin/settings/code-injection', data);
            toast.success("Code injection settings updated.");
        } catch (error) {
            toast.error("Failed to save settings.");
        } finally {
            setSaving(false);
        }
    };

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

            <SettingsLayout>
                <Card className="border-orange-200 dark:border-orange-900">
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Code className="w-5 h-5 text-orange-600" /> Header & Footer Code
                        </CardTitle>
                        <CardDescription>
                            Inject custom scripts (Analytics, Chat widgets, Pixel) globally.
                        </CardDescription>
                    </CardHeader>
                    
                    <CardContent className="space-y-6 pt-4">
                        
                        <div className="bg-orange-50 dark:bg-orange-950/20 p-4 rounded-md border border-orange-100 dark:border-orange-900/50 flex gap-3 text-sm text-orange-800 dark:text-orange-200">
                            <AlertTriangle className="w-5 h-5 shrink-0" />
                            <p>
                                <strong>Warning:</strong> Invalid HTML or JavaScript here can break your site layout or functionality. Please double-check your code before saving.
                            </p>
                        </div>

                        {loading ? (
                            <div className="flex justify-center py-8">
                                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                            </div>
                        ) : (
                            <>
                                <div className="space-y-3">
                                    <Label className="text-base">Header Code (Inside &lt;head&gt;)</Label>
                                    <p className="text-xs text-muted-foreground">
                                        Suitable for verification tags, CSS styles, and critical scripts.
                                    </p>
                                    <Textarea 
                                        value={data.header_code}
                                        onChange={(e) => setData({...data, header_code: e.target.value})}
                                        className="font-mono text-xs h-48 resize-y bg-muted/50"
                                        placeholder="<script>...</script>"
                                        spellCheck={false}
                                    />
                                </div>

                                <div className="space-y-3">
                                    <Label className="text-base">Footer Code (Before &lt;/body&gt;)</Label>
                                    <p className="text-xs text-muted-foreground">
                                        Best for Analytics, Chat widgets, and non-blocking JS.
                                    </p>
                                    <Textarea 
                                        value={data.footer_code}
                                        onChange={(e) => setData({...data, footer_code: e.target.value})}
                                        className="font-mono text-xs h-48 resize-y bg-muted/50"
                                        placeholder="<script>...</script>"
                                        spellCheck={false}
                                    />
                                </div>

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