import React from 'react';
import { Head, useForm } from '@inertiajs/react';
import { toast } from 'sonner';
import AdminLayout from '@/cp/Layouts/AdminLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/Components/ui/card";
import { Label } from "@/Components/ui/label";
import { Button } from "@/Components/ui/button";
import { Save, Code, AlertTriangle, Loader2 } from "lucide-react";

export default function CustomScripts({ settings }) {
    const { data, setData, post, processing } = useForm({
        custom_header_script: settings?.custom_header_script || '',
        custom_footer_script: settings?.custom_footer_script || '',
    });

    const submit = (e) => {
        e.preventDefault();
        post(route('cp.settings.scripts.update'), {
            preserveScroll: true,
            onSuccess: () => toast.success('Custom scripts updated successfully!'),
            onError: () => toast.error('Failed to save scripts.')
        });
    };

    return (
        <AdminLayout>
            <Head title="Custom Scripts & Analytics" />

            <div className="max-w-5xl mx-auto pb-12">
                <div className="flex items-center gap-3 mb-6">
                    <Code className="w-8 h-8 text-primary" />
                    <div>
                        <h2 className="text-2xl font-bold tracking-tight">Custom Scripts (Injectors)</h2>
                        <p className="text-muted-foreground">Add third-party tracking codes, CSS, or JavaScript globally.</p>
                    </div>
                </div>

                {/* Warning Alert */}
                <div className="bg-amber-500/10 border border-amber-500/30 text-amber-700 dark:text-amber-500 p-4 rounded-xl flex gap-3 items-start mb-6">
                    <AlertTriangle className="w-5 h-5 shrink-0 mt-0.5" />
                    <div className="text-sm leading-relaxed">
                        <strong>Warning:</strong> The code pasted here is injected directly into the HTML without filtering. Malformed tags or syntax errors in JavaScript could break the visual layout or functionality of the frontend. Only paste scripts from trusted sources (Google Analytics, Meta Pixel, Tawk.to, etc.).
                    </div>
                </div>

                <form onSubmit={submit} className="space-y-6">
                    {/* Header Scripts */}
                    <Card className="shadow-sm border-border/50">
                        <CardHeader className="bg-muted/10 border-b pb-4">
                            <CardTitle>Header Scripts (&lt;head&gt;)</CardTitle>
                            <CardDescription>
                                Scripts added here will be rendered just before the closing <code>&lt;/head&gt;</code> tag. Best for Google Analytics (GA4), Meta Pixel, custom CSS, or verification meta tags.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <div className="space-y-2">
                                <Label className="sr-only">Header Code</Label>
                                <textarea 
                                    value={data.custom_header_script} 
                                    onChange={(e) => setData('custom_header_script', e.target.value)} 
                                    placeholder={`<!-- Paste your Header HTML/JS here -->\n<script>\n  // Google Analytics code...\n</script>`} 
                                    className="w-full min-h-[250px] p-4 font-mono text-sm leading-relaxed bg-zinc-950 text-zinc-100 border border-border/50 rounded-xl focus:ring-primary focus:border-primary resize-y"
                                    spellCheck="false"
                                />
                            </div>
                        </CardContent>
                    </Card>

                    {/* Footer Scripts */}
                    <Card className="shadow-sm border-border/50">
                        <CardHeader className="bg-muted/10 border-b pb-4">
                            <CardTitle>Footer Scripts (&lt;body&gt;)</CardTitle>
                            <CardDescription>
                                Scripts added here will be rendered just before the closing <code>&lt;/body&gt;</code> tag. Best for Live Chat widgets (Tawk.to, Crisp), deferred JavaScript, or heavy tracking codes to avoid slowing down page load.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="pt-6">
                            <div className="space-y-2">
                                <Label className="sr-only">Footer Code</Label>
                                <textarea 
                                    value={data.custom_footer_script} 
                                    onChange={(e) => setData('custom_footer_script', e.target.value)} 
                                    placeholder={`<!-- Paste your Footer HTML/JS here -->\n<script>\n  // Tawk.to Live Chat code...\n</script>`} 
                                    className="w-full min-h-[250px] p-4 font-mono text-sm leading-relaxed bg-zinc-950 text-zinc-100 border border-border/50 rounded-xl focus:ring-primary focus:border-primary resize-y"
                                    spellCheck="false"
                                />
                            </div>
                        </CardContent>
                    </Card>

                    <div className="flex justify-end pt-4">
                        <Button type="submit" disabled={processing} className="gap-2 min-w-[160px] shadow-sm" size="lg">
                            {processing ? <Loader2 className="w-5 h-5 animate-spin" /> : <Save className="w-5 h-5" />}
                            {processing ? 'Saving...' : 'Save Scripts'}
                        </Button>
                    </div>
                </form>
            </div>
        </AdminLayout>
    );
}