import React, { useState, useEffect, useRef } from 'react';
import { Head } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';

import AdminLayout from '@/Admin/Layouts/AdminLayout';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import ConfirmModal from '@/Components/ConfirmModal';

// --- PARTIALS ---
import NewsToolbar from './Partials/NewsToolbar';
import NewsTable from './Partials/NewsTable';
import EditPostDialog from './Partials/EditPostDialog';

export default function NewsManager() {
    // --- STATE ---
    const [posts, setPosts] = useState([]);
    const [pagination, setPagination] = useState({});
    const [loading, setLoading] = useState(true);
    
    // Filters
    const [search, setSearch] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [sourceFilter, setSourceFilter] = useState('all'); 
    const [page, setPage] = useState(1);

    // Modals
    const [isEditOpen, setIsEditOpen] = useState(false);
    const [editingPost, setEditingPost] = useState(null);
    const [deleteId, setDeleteId] = useState(null);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);

    // Data for Edit Modal
    const [categories, setCategories] = useState([]);

    const isInitialMount = useRef(true);

    // --- EFFECTS ---

    // 1. Handle Filter, Page Changes & Initial Load
    useEffect(() => {
        fetchPosts();
    }, [statusFilter, sourceFilter, page]); 

    // 2. Handle Search (Debounced)
    useEffect(() => {
        if (isInitialMount.current) {
            isInitialMount.current = false;
            return;
        }

        const timer = setTimeout(() => {
            if (page === 1) {
                fetchPosts(); 
            } else {
                setPage(1); 
            }
        }, 500);

        return () => clearTimeout(timer);
    }, [search]);

    // 3. Load Categories once
    useEffect(() => {
        fetchCategories();
    }, []);

    // --- API CALLS ---
    const fetchPosts = async () => {
        setLoading(true);
        try {
            const res = await axios.get('/api/admin/posts', {
                params: { 
                    search, 
                    status: statusFilter,
                    source: sourceFilter, 
                    page 
                }
            });
            setPosts(res.data.data);
            setPagination(res.data);
        } catch (error) {
            toast.error("Failed to load posts");
        } finally {
            setLoading(false);
        }
    };

    const fetchCategories = async () => {
        try {
            const res = await axios.get('/api/admin/categories?tree=true');
            setCategories(res.data);
        } catch (error) {
            console.error("Failed to load categories");
        }
    };

    // --- ACTIONS ---
    const handleDelete = async () => {
        if (!deleteId) return;
        try {
            await axios.delete(`/api/admin/posts/${deleteId}`);
            toast.success("Post deleted successfully");
            fetchPosts();
        } catch (error) {
            toast.error("Failed to delete post");
        } finally {
            setIsDeleteOpen(false);
            setDeleteId(null);
        }
    };

    const openEdit = (post) => {
        setEditingPost(post);
        setIsEditOpen(true);
    };

    const confirmDelete = (id) => {
        setDeleteId(id);
        setIsDeleteOpen(true);
    };

    return (
        <AdminLayout header="News Management">
            <Head title="Manage News" />

            <ConfirmModal 
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={handleDelete}
                title="Delete Post"
                description="This will permanently delete the article and its images."
                confirmText="Delete Post"
                variant="destructive"
            />

            <EditPostDialog 
                open={isEditOpen}
                onOpenChange={setIsEditOpen}
                post={editingPost}
                categories={categories}
                onSuccess={fetchPosts}
            />

            <div className="space-y-6">
                <div>
                    <h2 className="text-3xl font-bold tracking-tight">News Management</h2>
                    <p className="text-muted-foreground">Review, edit, and manage all news articles.</p>
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>Article Database</CardTitle>
                        <CardDescription>Total Records: {pagination.total || 0}</CardDescription>
                    </CardHeader>
                    <CardContent>
                        
                        <NewsToolbar 
                            search={search} 
                            setSearch={setSearch} 
                            statusFilter={statusFilter} 
                            setStatusFilter={(val) => { setStatusFilter(val); setPage(1); }} 
                            sourceFilter={sourceFilter} 
                            setSourceFilter={(val) => { setSourceFilter(val); setPage(1); }} 
                        />

                        <NewsTable 
                            posts={posts} 
                            loading={loading} 
                            onEdit={openEdit} 
                            onDelete={confirmDelete} 
                        />

                        <div className="flex items-center justify-end space-x-2 py-4">
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => setPage(p => Math.max(1, p - 1))}
                                disabled={!pagination.prev_page_url || loading}
                            >
                                Previous
                            </Button>
                            <span className="text-sm text-muted-foreground">
                                Page {pagination.current_page} of {pagination.last_page}
                            </span>
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => setPage(p => p + 1)}
                                disabled={!pagination.next_page_url || loading}
                            >
                                Next
                            </Button>
                        </div>

                    </CardContent>
                </Card>
            </div>
        </AdminLayout>
    );
}