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 { Separator } from "@/components/ui/separator";
import { Loader2, Save, LayoutTemplate, MessageSquare, Link as LinkIcon, Sidebar } from 'lucide-react'; 
import axios from 'axios';
import { toast } from 'sonner';

export default function PostSettings({ auth }) {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    
    const [settings, setSettings] = useState({
        submission_enabled: false,
        auto_approval: false,
        enable_inline_related: true, 
        comments_enabled: true, 
        quick_fetch_enabled: true, 
        show_right_sidebar: true, 
    });

    useEffect(() => {
        axios.get('/api/admin/settings/post')
            .then(response => {
                setSettings({
                    submission_enabled: response.data.submission_enabled === 'true',
                    auto_approval: response.data.auto_approval === 'true',
                    enable_inline_related: response.data.enable_inline_related !== 'false',
                    comments_enabled: response.data.comments_enabled !== 'false',
                    quick_fetch_enabled: response.data.quick_fetch_enabled !== 'false', 
                    show_right_sidebar: response.data.show_right_sidebar !== 'false', 
                });
            })
            .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/post', {
                submission_enabled: settings.submission_enabled ? 'true' : 'false',
                auto_approval: settings.auto_approval ? 'true' : 'false',
                enable_inline_related: settings.enable_inline_related ? 'true' : 'false',
                comments_enabled: settings.comments_enabled ? 'true' : 'false', 
                quick_fetch_enabled: settings.quick_fetch_enabled ? 'true' : 'false', 
                show_right_sidebar: settings.show_right_sidebar ? 'true' : 'false', 
            });
            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="Post Configuration" />

            <SettingsLayout>
                <Card>
                    <CardHeader>
                        <CardTitle>Post & Display Configuration</CardTitle>
                        <CardDescription>
                            Manage submission rules, comments, and article layout features.
                        </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>
                        ) : (
                            <>
                                {/* Submission Rules */}
                                <div className="space-y-4">
                                    <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">Submission Rules</h3>
                                    <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">Allow User Submissions</Label>
                                            <p className="text-sm text-muted-foreground">Users can submit new stories via the dashboard.</p>
                                        </div>
                                        <Switch 
                                            checked={settings.submission_enabled}
                                            onCheckedChange={(checked) => setSettings(prev => ({ ...prev, submission_enabled: checked }))}
                                        />
                                    </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 flex items-center gap-2">
                                                <LinkIcon className="w-4 h-4" /> Quick Fetch Article URL
                                            </Label>
                                            <p className="text-sm text-muted-foreground">
                                                Allow general users to auto-extract articles via URL. (Admins bypass this restriction).
                                            </p>
                                        </div>
                                        <Switch 
                                            checked={settings.quick_fetch_enabled}
                                            onCheckedChange={(checked) => setSettings(prev => ({ ...prev, quick_fetch_enabled: checked }))}
                                        />
                                    </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">Auto-Approve Posts</Label>
                                            <p className="text-sm text-muted-foreground">Publish submitted stories immediately without admin review.</p>
                                        </div>
                                        <Switch 
                                            checked={settings.auto_approval}
                                            onCheckedChange={(checked) => setSettings(prev => ({ ...prev, auto_approval: checked }))}
                                        />
                                    </div>
                                </div>

                                <Separator />

                                {/* Layout & Interaction Features */}
                                <div className="space-y-4">
                                    <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider flex items-center gap-2">
                                        <LayoutTemplate className="w-4 h-4" /> Layout & Interaction
                                    </h3>
                                    
                                    <div className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm bg-muted/10">
                                        <div className="space-y-0.5">
                                            <Label className="text-base flex items-center gap-2">
                                                <Sidebar className="w-4 h-4" /> Show Right Sidebar
                                            </Label>
                                            <p className="text-sm text-muted-foreground">
                                                Display the right sidebar (trending, related, ads) on the single article page.
                                            </p>
                                        </div>
                                        <Switch 
                                            checked={settings.show_right_sidebar}
                                            onCheckedChange={(checked) => setSettings(prev => ({ ...prev, show_right_sidebar: checked }))}
                                        />
                                    </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 flex items-center gap-2">
                                                <MessageSquare className="w-4 h-4" /> Enable Comments
                                            </Label>
                                            <p className="text-sm text-muted-foreground">
                                                Allow users to post comments on articles globally.
                                            </p>
                                        </div>
                                        <Switch 
                                            checked={settings.comments_enabled}
                                            onCheckedChange={(checked) => setSettings(prev => ({ ...prev, comments_enabled: checked }))}
                                        />
                                    </div>

                                    <div className="flex flex-row items-center justify-between rounded-lg border p-4 shadow-sm bg-muted/20">
                                        <div className="space-y-0.5">
                                            <Label className="text-base">Inline Related News</Label>
                                            <p className="text-sm text-muted-foreground">
                                                Show a "More in Category" widget inside the article content (after the 5th paragraph).
                                            </p>
                                        </div>
                                        <Switch 
                                            checked={settings.enable_inline_related}
                                            onCheckedChange={(checked) => setSettings(prev => ({ ...prev, enable_inline_related: checked }))}
                                        />
                                    </div>
                                </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>
    );
}