import { useEffect, useState } from 'react';
import { Head, Link } from '@inertiajs/react';
import axios from 'axios';
import { toast } from 'sonner';
import { Edit, Trash2, Eye, Clock, CheckCircle2, XCircle, PlusCircle, ExternalLink, Calendar } from 'lucide-react';

import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Button } from '@/Components/ui/button';
import { Badge } from '@/Components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/Components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/Components/ui/tabs";
import { Card, CardContent, CardHeader } from '@/Components/ui/card';
import { Skeleton } from '@/Components/ui/skeleton';
import ConfirmModal from '@/Components/ConfirmModal';
import useTranslation from '@/hooks/useTranslation'; 

export default function MyPosts() {
    const { t } = useTranslation(); 
    const [posts, setPosts] = useState([]);
    const [pagination, setPagination] = useState({});
    const [loading, setLoading] = useState(true);
    const[statusFilter, setStatusFilter] = useState('all');
    const [page, setPage] = useState(1);
    const [deleteId, setDeleteId] = useState(null);
    const[isDeleteOpen, setIsDeleteOpen] = useState(false);

    useEffect(() => {
        fetchPosts();
    },[page, statusFilter]);

    const fetchPosts = async () => {
        setLoading(true);
        try {
            const res = await axios.get('/api/user/my-posts', { 
                params: { 
                    page, 
                    status: statusFilter 
                } 
            });
            setPosts(res.data.data);
            setPagination(res.data);
        } catch (error) {
            toast.error(t('_fetch_failed', 'Failed to fetch your posts'));
        } finally {
            setLoading(false);
        }
    };

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

    const handleDelete = async () => {
        if (!deleteId) return;
        try {
            await axios.delete(`/api/user/my-posts/${deleteId}`);
            toast.success(t('_deleted_success', 'Post deleted successfully'));
            if (posts.length === 1 && page > 1) {
                setPage(page - 1);
            } else {
                fetchPosts(); 
            }
        } catch (error) {
            toast.error(t('_delete_failed', 'Failed to delete post'));
        } finally {
            setIsDeleteOpen(false);
            setDeleteId(null);
        }
    };

    return (
        <AuthenticatedLayout>
            <Head title={t('_my_posts', 'My Posts')} />

            <ConfirmModal 
                open={isDeleteOpen}
                onOpenChange={setIsDeleteOpen}
                onConfirm={handleDelete}
                title={t('_delete_post', 'Delete Post')}
                description={t('_delete_warning', 'Are you sure? This will permanently delete your article and cannot be undone.')}
                confirmText={t('_yes_delete', 'Yes, Delete')}
                variant="destructive"
            />

            <div className="max-w-5xl mx-auto">
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
                    <div>
                        <h2 className="text-3xl font-bold tracking-tight">{t('_my_posts', 'My Posts')}</h2>
                        <p className="text-muted-foreground">{t('_manage_submissions', 'Manage your submissions and view their status.')}</p>
                    </div>
                    <Button asChild>
                        <Link href={route('news.submit')}>
                            <PlusCircle className="me-2 h-4 w-4" /> {t('_new_post', 'New Post')}
                        </Link>
                    </Button>
                </div>

                <Card>
                    <CardHeader>
                        <Tabs value={statusFilter} onValueChange={(val) => { setStatusFilter(val); setPage(1); }}>
                            <TabsList className="grid w-full grid-cols-4">
                                <TabsTrigger value="all">{t('_all', 'All')}</TabsTrigger>
                                <TabsTrigger value="pending">{t('_pending', 'Pending')}</TabsTrigger>
                                <TabsTrigger value="published">{t('_published', 'Published')}</TabsTrigger>
                                <TabsTrigger value="rejected">{t('_rejected', 'Rejected')}</TabsTrigger>
                            </TabsList>
                        </Tabs>
                    </CardHeader>
                    <CardContent>
                        <div className="border rounded-md overflow-x-auto w-full relative">
                            <Table className="min-w-[800px]">
                                <TableHeader>
                                    <TableRow>
                                        <TableHead className="w-[120px] whitespace-nowrap">{t('_status', 'Status')}</TableHead>
                                        <TableHead className="min-w-[250px] max-w-[400px]">{t('_title', 'Title')}</TableHead>
                                        <TableHead className="whitespace-nowrap">{t('_date', 'Date')}</TableHead>
                                        <TableHead className="text-center whitespace-nowrap">{t('_views', 'Views')}</TableHead>
                                        <TableHead className="text-right whitespace-nowrap">{t('_actions', 'Actions')}</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {loading ? (
                                        Array.from({ length: 5 }).map((_, index) => (
                                            <TableRow key={`skeleton-${index}`}>
                                                <TableCell>
                                                    <Skeleton className="h-6 w-20 rounded-full" />
                                                </TableCell>
                                                <TableCell>
                                                    <Skeleton className="h-4 w-3/4 max-w-[300px]" />
                                                </TableCell>
                                                <TableCell>
                                                    <Skeleton className="h-4 w-24" />
                                                </TableCell>
                                                <TableCell className="text-center">
                                                    <div className="flex items-center justify-center gap-2">
                                                        <Skeleton className="h-4 w-4 rounded-full" />
                                                        <Skeleton className="h-4 w-8" />
                                                    </div>
                                                </TableCell>
                                                <TableCell className="text-right">
                                                    <div className="flex justify-end items-center gap-2">
                                                        <Skeleton className="h-8 w-8 rounded-md" />
                                                        <Skeleton className="h-8 w-8 rounded-md" />
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    ) : posts.length === 0 ? (
                                        <TableRow><TableCell colSpan={5} className="h-24 text-center text-muted-foreground">{t('_no_posts_yet', "You haven't submitted any posts yet.")}</TableCell></TableRow>
                                    ) : posts.map(post => (
                                        <TableRow key={post.id} className="group hover:bg-muted/50 transition-colors">
                                            <TableCell><StatusBadge status={post.status} t={t} /></TableCell>
                                            
                                            <TableCell className="font-medium max-w-[250px] sm:max-w-[400px] truncate" title={post.title}>
                                                {post.title}
                                            </TableCell>
                                            
                                            {/* Publish Date Column */}
                                            <TableCell className="whitespace-nowrap text-muted-foreground text-sm">
                                                <div className="flex items-center gap-1.5">
                                                    <Calendar className="w-3.5 h-3.5" />
                                                    {new Date(post.created_at).toLocaleDateString(undefined, { 
                                                        year: 'numeric', 
                                                        month: 'short', 
                                                        day: 'numeric' 
                                                    })}
                                                </div>
                                            </TableCell>

                                            {/* View Count Column */}
                                            <TableCell className="text-center">
                                                <div className="inline-flex items-center justify-center gap-1.5 text-muted-foreground bg-muted/40 px-2.5 py-1 rounded-md text-xs font-medium border border-border">
                                                    <Eye className="h-3.5 w-3.5" />
                                                    {post.views_count.toLocaleString()}
                                                </div>
                                            </TableCell>

                                            {/* Actions Column */}
                                            <TableCell className="text-right whitespace-nowrap">
                                                {post.status === 'published' && (
                                                    <Button variant="ghost" size="sm" asChild>
                                                        <a href={post.route_url} target="_blank" rel="noopener noreferrer" title={t('_view_live', 'View Live')}>
                                                            <ExternalLink className="h-4 w-4 text-blue-600 hover:text-blue-800" />
                                                            <span className="sr-only sm:not-sr-only sm:ms-2">{t('_view', 'View')}</span>
                                                        </a>
                                                    </Button>
                                                )}

                                                <Button variant="ghost" size="sm" asChild>
                                                    <Link href={route('my-posts.edit', post.id)}>
                                                        <Edit className="h-4 w-4" />
                                                        <span className="sr-only sm:not-sr-only sm:ms-2">{t('_edit', 'Edit')}</span>
                                                    </Link>
                                                </Button>
                                                
                                                <Button variant="ghost" size="sm" className="text-red-600 hover:text-red-700 hover:bg-red-50" onClick={() => confirmDelete(post.id)}>
                                                    <Trash2 className="h-4 w-4" />
                                                     <span className="sr-only sm:not-sr-only sm:ms-2">{t('_delete', 'Delete')}</span>
                                                </Button>
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </div>

                        {/* Pagination */}
                        <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}
                            >
                                {t('_previous', 'Previous')}
                            </Button>
                            <span className="text-sm text-muted-foreground">
                                {t('_page_of', 'Page {current} of {total}').replace('{current}', pagination.current_page || 1).replace('{total}', pagination.last_page || 1)}
                            </span>
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={() => setPage(p => p + 1)}
                                disabled={!pagination.next_page_url || loading}
                            >
                                {t('_next', 'Next')}
                            </Button>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </AuthenticatedLayout>
    );
}

// Helper Component for Status Badges
function StatusBadge({ status, t }) {
    const styles = {
        pending: "bg-yellow-100 text-yellow-800 hover:bg-yellow-100 dark:bg-yellow-900/30 dark:text-yellow-500",
        published: "bg-green-100 text-green-800 hover:bg-green-100 dark:bg-green-900/30 dark:text-green-500",
        rejected: "bg-red-100 text-red-800 hover:bg-red-100 dark:bg-red-900/30 dark:text-red-500",
    };
    
    const icons = {
        pending: <Clock className="w-3 h-3 me-1" />, 
        published: <CheckCircle2 className="w-3 h-3 me-1" />, 
        rejected: <XCircle className="w-3 h-3 me-1" /> 
    };

    const statusLabels = {
        pending: t('_status_pending', 'Pending'),
        published: t('_status_published', 'Published'),
        rejected: t('_status_rejected', 'Rejected'),
    };

    return (
        <Badge variant="outline" className={`border-0 ${styles[status] || ''}`}>
            {icons[status]}
            <span className="capitalize whitespace-nowrap">{statusLabels[status] || status}</span>
        </Badge>
    );
}