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, CardFooter } from "@/Components/ui/card";
import { Button } from "@/Components/ui/button";
import { Label } from "@/Components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/Components/ui/radio-group";
import { Loader2, Save, Link2, AlertCircle } from 'lucide-react';
import axios from 'axios';
import { toast } from 'sonner';

export default function Permalinks() {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [structure, setStructure] = useState('default');

    // Load current settings from backend
    useEffect(() => {
        axios.get('/api/admin/settings/permalinks')
            .then(res => setStructure(res.data.post_structure))
            .catch(() => toast.error("Failed to load settings."))
            .finally(() => setLoading(false));
    },[]);

    // Save changes
    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            const res = await axios.post('/api/admin/settings/permalinks', {
                post_structure: structure
            });
            toast.success(res.data.message || "Permalink settings updated successfully!");
        } catch (error) {
            console.error(error);
            toast.error("Failed to update permalink settings.");
        } finally {
            setSaving(false);
        }
    };

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

            <SettingsLayout>
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Link2 className="w-5 h-5 text-primary" /> Permalink Structure (URLs)
                        </CardTitle>
                        <CardDescription>
                            Choose how your news article URLs are generated. Changing this will only affect newly published articles.
                        </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>
                        ) : (
                            <form id="permalink-form" onSubmit={handleSave} className="space-y-6">
                                
                                {/* Info Notice */}
                                <div className="bg-blue-50 dark:bg-blue-900/20 text-blue-800 dark:text-blue-200 p-4 rounded-md flex items-start gap-3 text-sm border border-blue-200 dark:border-blue-800">
                                    <AlertCircle className="w-5 h-5 shrink-0 mt-0.5" />
                                    <div className="space-y-1">
                                        <p className="font-semibold">Backward Compatibility is Active</p>
                                        <p>
                                            Do not worry about 404 errors! Old article links will continue to work perfectly even if you change the structure for new posts.
                                        </p>
                                    </div>
                                </div>

                                {/* Options */}
                                <div className="space-y-4">
                                    <Label className="text-base font-semibold">Post URL Structure</Label>
                                    <RadioGroup value={structure} onValueChange={setStructure} className="space-y-3">
                                        
                                        {/* Option 1: Default */}
                                        <div className={`flex items-start space-x-3 space-y-0 rounded-md border p-4 transition-colors ${structure === 'default' ? 'bg-primary/5 border-primary' : 'bg-card'}`}>
                                            <RadioGroupItem value="default" id="opt-default" className="mt-1" />
                                            <div className="space-y-1 w-full">
                                                <Label htmlFor="opt-default" className="font-bold cursor-pointer text-base">Default (Slug + Hash)</Label>
                                                <p className="text-sm text-muted-foreground">Generates a slug from English titles and appends a unique hash.</p>
                                                <div className="mt-2 p-2 bg-muted rounded font-mono text-xs text-muted-foreground break-all">
                                                    Example: <span className="text-foreground">yourdomain.com/news/my-first-post-64a2b1</span>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Option 2: Clean Slug (Unicode Support) */}
                                        <div className={`flex items-start space-x-3 space-y-0 rounded-md border p-4 transition-colors ${structure === 'slug_only' ? 'bg-primary/5 border-primary' : 'bg-card'}`}>
                                            <RadioGroupItem value="slug_only" id="opt-slug" className="mt-1" />
                                            <div className="space-y-1 w-full">
                                                <Label htmlFor="opt-slug" className="font-bold cursor-pointer text-base">Clean Slug (Unicode / Multi-language Support)</Label>
                                                <p className="text-sm text-muted-foreground">Removes the hash. Fully supports Bengali, Arabic, and other unicode languages natively. Adds a number only if the title already exists.</p>
                                                <div className="mt-2 p-2 bg-muted rounded font-mono text-xs text-muted-foreground break-all space-y-1">
                                                    <p>Example: <span className="text-foreground">yourdomain.com/news/my-first-post</span></p>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Option 3: Post ID Only */}
                                        <div className={`flex items-start space-x-3 space-y-0 rounded-md border p-4 transition-colors ${structure === 'post_id' ? 'bg-primary/5 border-primary' : 'bg-card'}`}>
                                            <RadioGroupItem value="post_id" id="opt-id" className="mt-1" />
                                            <div className="space-y-1 w-full">
                                                <Label htmlFor="opt-id" className="font-bold cursor-pointer text-base">Post ID Only</Label>
                                                <p className="text-sm text-muted-foreground">Creates short, clean URLs using only the unique ID of the post.</p>
                                                <div className="mt-2 p-2 bg-muted rounded font-mono text-xs text-muted-foreground break-all">
                                                    Example: <span className="text-foreground">yourdomain.com/post/12345</span>
                                                </div>
                                            </div>
                                        </div>

                                    </RadioGroup>
                                </div>
                            </form>
                        )}
                    </CardContent>

                    <CardFooter className="border-t px-6 py-4">
                        <Button type="submit" form="permalink-form" disabled={saving || loading} className="min-w-[150px]">
                            {saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
                            Save Settings
                        </Button>
                    </CardFooter>
                </Card>
            </SettingsLayout>
        </AdminLayout>
    );
}