import { useEffect, useState } from 'react';
import { Head, Link } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { PlusCircle, MoreHorizontal, Trash2, Edit, Search } from 'lucide-react';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import { Button } from '@/Components/ui/button';
import { Badge } from '@/Components/ui/badge';
import { Input } from '@/Components/ui/input';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/Components/ui/dropdown-menu";
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import ConfirmModal from '@/Components/ConfirmModal'; 

export default function PageList() {
    const[pages, setPages] = useState([]);
    const [pagination, setPagination] = useState({});
    const[loading, setLoading] = useState(true);
    const [page, setPage] = useState(1);
    const [searchQuery, setSearchQuery] = useState('');

    // --- State for Delete Confirmation ---
    const[deleteId, setDeleteId] = useState(null);
    const [isDeleteOpen, setIsDeleteOpen] = useState(false);

    useEffect(() => {
        const timer = setTimeout(() => {
            fetchPages();
        }, 300); // Debounce for search
        return () => clearTimeout(timer);
    }, [page, searchQuery]);

    const fetchPages = () => {
        setLoading(true);
        axios.get(`/api/admin/pages?page=${page}&search=${searchQuery}`)
            .then(response => {
                setPages(response.data.data);
                setPagination(response.data);
            })
            .catch(() => toast.error("Failed to load pages"))
            .finally(() => setLoading(false));
    };

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

    const handleDelete = async () => {
        if (!deleteId) return;

        try {
            await axios.delete(`/api/admin/pages/${deleteId}`);
            toast.success("Page deleted successfully");
            
            // Go to previous page if we delete the last item on current page
            if (pages.length === 1 && page > 1) {
                setPage(page - 1);
            } else {
                fetchPages();
            }
        } catch (error) {
            toast.error("Failed to delete page");
        } finally {
            setIsDeleteOpen(false);
            setDeleteId(null);
        }
    };

    return (
        <AdminLayout>
            <Head title="Custom Pages" />

            <ConfirmModal 
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={handleDelete}
                title="Delete Page"
                description="Are you sure you want to delete this page? This action cannot be undone."
                confirmText="Delete Page"
                variant="destructive"
            />

            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                <div>
                    <h2 className="text-3xl font-bold tracking-tight">Custom Pages</h2>
                    <p className="text-muted-foreground">Create and manage static pages.</p>
                </div>
                <Button asChild>
                    <Link href={route('admin.pages.create')}>
                        <PlusCircle className="mr-2 h-4 w-4" /> Create Page
                    </Link>
                </Button>
            </div>

            <Card>
                <CardHeader className="flex flex-row items-center justify-between border-b pb-4 mb-4">
                    <CardTitle>All Pages</CardTitle>
                    <div className="relative w-full max-w-sm">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                        <Input 
                            placeholder="Search pages..." 
                            className="pl-9"
                            value={searchQuery}
                            onChange={(e) => { setSearchQuery(e.target.value); setPage(1); }}
                        />
                    </div>
                </CardHeader>
                <CardContent>
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Title</TableHead>
                                <TableHead>Slug</TableHead>
                                <TableHead>Status</TableHead>
                                <TableHead>Last Updated</TableHead>
                                <TableHead className="text-right">Actions</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {loading ? (
                                <TableRow><TableCell colSpan={5} className="h-24 text-center">Loading...</TableCell></TableRow>
                            ) : pages.length === 0 ? (
                                <TableRow><TableCell colSpan={5} className="h-24 text-center text-muted-foreground">No pages found.</TableCell></TableRow>
                            ) : pages.map((page) => (
                                <TableRow key={page.id}>
                                    <TableCell className="font-medium">{page.title}</TableCell>
                                    <TableCell className="text-muted-foreground">/{page.slug}</TableCell>
                                    <TableCell>
                                        <Badge variant={page.status === 'published' ? 'default' : 'secondary'}>
                                            {page.status}
                                        </Badge>
                                    </TableCell>
                                    <TableCell>{new Date(page.updated_at).toLocaleDateString()}</TableCell>
                                    <TableCell className="text-right">
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button variant="ghost" className="h-8 w-8 p-0">
                                                    <MoreHorizontal className="h-4 w-4" />
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuItem asChild>
                                                    <Link href={route('admin.pages.edit', page.id)}>
                                                        <Edit className="mr-2 h-4 w-4" /> Edit
                                                    </Link>
                                                </DropdownMenuItem>
                                                <DropdownMenuItem 
                                                    onClick={() => confirmDelete(page.id)} 
                                                    className="text-red-600 focus:text-red-600"
                                                >
                                                    <Trash2 className="mr-2 h-4 w-4" /> Delete
                                                </DropdownMenuItem>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </TableCell>
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>

                    {/* Pagination Controls */}
                    <div className="flex items-center justify-end space-x-2 pt-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 || 1} of {pagination.last_page || 1}
                        </span>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => setPage(p => p + 1)}
                            disabled={!pagination.next_page_url || loading}
                        >
                            Next
                        </Button>
                    </div>
                </CardContent>
            </Card>
        </AdminLayout>
    );
}