import React, { useEffect, useState } from 'react';
import { Head, Link } from '@inertiajs/react';
import AdminLayout from '@/Admin/Layouts/AdminLayout';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Users, FileText, Clock, Eye, TrendingUp, MoreHorizontal, ArrowUpRight } from 'lucide-react';
import axios from 'axios';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

export default function Dashboard() {
    const [data, setData] = useState({
        stats: {},
        activity: { recent_posts: [], recent_users: [] },
        chart: []
    });
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        axios.get('/api/admin/dashboard-stats')
            .then(res => setData(res.data))
            .catch(err => console.error(err))
            .finally(() => setLoading(false));
    }, []);

    const { stats, activity, chart } = data;

    const getStatusColor = (status) => {
        switch(status) {
            case 'published': return 'bg-green-100 text-green-700 hover:bg-green-100 border-green-200';
            case 'pending': return 'bg-yellow-100 text-yellow-700 hover:bg-yellow-100 border-yellow-200';
            case 'rejected': return 'bg-red-100 text-red-700 hover:bg-red-100 border-red-200';
            default: return 'bg-gray-100 text-gray-700';
        }
    };

    return (
        <AdminLayout>
            <Head title="Admin Dashboard" />
            
            <div className="space-y-6">
                <h2 className="text-3xl font-bold tracking-tight">Dashboard</h2>
                
                {/* --- TOP STATS --- */}
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                            <CardTitle className="text-sm font-medium">Total Users</CardTitle>
                            <Users className="h-4 w-4 text-muted-foreground" />
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">{stats.total_users || 0}</div>
                            <p className="text-xs text-muted-foreground">+2% from last month</p>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                            <CardTitle className="text-sm font-medium">Total Posts</CardTitle>
                            <FileText className="h-4 w-4 text-muted-foreground" />
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">{stats.total_posts || 0}</div>
                            <p className="text-xs text-muted-foreground">+12 since yesterday</p>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                            <CardTitle className="text-sm font-medium">Pending Review</CardTitle>
                            <Clock className="h-4 w-4 text-muted-foreground" />
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">{stats.pending_posts || 0}</div>
                            <p className="text-xs text-muted-foreground">Requires attention</p>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                            <CardTitle className="text-sm font-medium">Total Views</CardTitle>
                            <Eye className="h-4 w-4 text-muted-foreground" />
                        </CardHeader>
                        <CardContent>
                            <div className="text-2xl font-bold">{(stats.total_views || 0).toLocaleString()}</div>
                            <p className="text-xs text-muted-foreground">Lifetime page views</p>
                        </CardContent>
                    </Card>
                </div>

                {/* --- CHART SECTION --- */}
                <div className="grid gap-4 md:grid-cols-7">
                    <Card className="col-span-4">
                        <CardHeader>
                            <CardTitle>Post Analytics</CardTitle>
                            <CardDescription>
                                Content creation trend over the last 7 days.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="pl-2">
                            <div className="h-[300px] w-full">
                                <ResponsiveContainer width="100%" height="100%">
                                    <AreaChart data={chart}>
                                        <defs>
                                            <linearGradient id="colorCount" x1="0" y1="0" x2="0" y2="1">
                                                <stop offset="5%" stopColor="#8884d8" stopOpacity={0.8}/>
                                                <stop offset="95%" stopColor="#8884d8" stopOpacity={0}/>
                                            </linearGradient>
                                        </defs>
                                        <XAxis 
                                            dataKey="date" 
                                            stroke="#888888" 
                                            fontSize={12} 
                                            tickLine={false} 
                                            axisLine={false} 
                                        />
                                        <YAxis 
                                            stroke="#888888" 
                                            fontSize={12} 
                                            tickLine={false} 
                                            axisLine={false} 
                                            allowDecimals={false}
                                        />
                                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
                                        <Tooltip 
                                            contentStyle={{ backgroundColor: 'hsl(var(--popover))', borderColor: 'hsl(var(--border))', borderRadius: '8px' }} 
                                            itemStyle={{ color: 'hsl(var(--popover-foreground))' }}
                                        />
                                        <Area 
                                            type="monotone" 
                                            dataKey="count" 
                                            stroke="#8884d8" 
                                            fillOpacity={1} 
                                            fill="url(#colorCount)" 
                                        />
                                    </AreaChart>
                                </ResponsiveContainer>
                            </div>
                        </CardContent>
                    </Card>

                    {/* --- RECENT USERS --- */}
                    <Card className="col-span-3">
                        <CardHeader>
                            <CardTitle>Recent Users</CardTitle>
                            <CardDescription>
                                Newest members joined this week.
                            </CardDescription>
                        </CardHeader>
                        <CardContent>
                            <div className="space-y-8">
                                {activity.recent_users.map((user) => (
                                    <div className="flex items-center" key={user.id}>
                                        <Avatar className="h-9 w-9">
                                            <AvatarImage src={user.avatar} alt={user.name} />
                                            <AvatarFallback>{user.name.charAt(0)}</AvatarFallback>
                                        </Avatar>
                                        <div className="ml-4 space-y-1">
                                            <p className="text-sm font-medium leading-none">{user.name}</p>
                                            <p className="text-xs text-muted-foreground">{user.email}</p>
                                        </div>
                                        <div className="ml-auto font-medium text-xs text-muted-foreground capitalize">
                                            {user.role}
                                        </div>
                                    </div>
                                ))}
                                {activity.recent_users.length === 0 && (
                                    <div className="text-center text-sm text-muted-foreground py-4">No recent users.</div>
                                )}
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* --- LATEST POSTS TABLE --- */}
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between">
                        <div>
                            <CardTitle>Latest Posts</CardTitle>
                            <CardDescription>Recently submitted articles.</CardDescription>
                        </div>
                        <Link href={route('admin.news.index')} className="text-sm text-primary hover:underline flex items-center">
                            View All <ArrowUpRight className="ml-1 h-4 w-4" />
                        </Link>
                    </CardHeader>
                    <CardContent>
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Title</TableHead>
                                    <TableHead>Status</TableHead>
                                    <TableHead>Author</TableHead>
                                    <TableHead className="text-right">Views</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {activity.recent_posts.map((post) => (
                                    <TableRow key={post.id}>
                                        <TableCell className="font-medium max-w-[300px] truncate">
                                            {post.title}
                                        </TableCell>
                                        <TableCell>
                                            <Badge variant="outline" className={`border-0 ${getStatusColor(post.status)}`}>
                                                {post.status}
                                            </Badge>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex items-center gap-2">
                                                <Avatar className="h-6 w-6">
                                                    <AvatarImage src={post.user?.avatar} />
                                                    <AvatarFallback>{post.user?.name?.charAt(0)}</AvatarFallback>
                                                </Avatar>
                                                <span className="text-xs">{post.user?.name}</span>
                                            </div>
                                        </TableCell>
                                        <TableCell className="text-right">
                                            {post.views_count}
                                        </TableCell>
                                    </TableRow>
                                ))}
                                {activity.recent_posts.length === 0 && (
                                    <TableRow>
                                        <TableCell colSpan={4} className="h-24 text-center text-muted-foreground">
                                            No recent posts found.
                                        </TableCell>
                                    </TableRow>
                                )}
                            </TableBody>
                        </Table>
                    </CardContent>
                </Card>
            </div>
        </AdminLayout>
    );
}