import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import AdminLayout from '@/components/Layouts/AdminLayout';
import Card from '@/components/Card/Card';
import Button from '@/components/Button/Button';
import RefreshButton from '@/components/RefreshButton/RefreshButton';
import Table, { TableBody, TableCell, TableHeader, TableHeaderCell, TableRow } from '@/components/Table/Table';
import Modal from '@/components/Modal/Modal';

interface Session {
    id: string;
    user_id: number;
    user_name: string;
    user_email: string;
    user_role: string;
    ip_address: string;
    user_agent: string;
    last_activity: string;
    last_activity_timestamp: number;
}

interface SessionsPageProps {
    sessions: Session[];
    pagination?: {
        data: Session[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
        links: Array<{ url: string | null; label: string; active: boolean }>;
    };
}

export default function Index({ sessions = [], pagination }: SessionsPageProps) {
    const { props: pageProps } = usePage();
    
    // Debug: Always log to ensure component is rendered
    console.log('Sessions Index Component Rendered');
    console.log('Destructured Props:', { sessions: sessions.length, pagination });
    console.log('Page Props:', pageProps);
    console.log('Pagination from Page Props:', (pageProps as any).pagination);
    
    // Use pagination from pageProps if destructured pagination is undefined
    const actualPagination = pagination || (pageProps as any).pagination;
    
    // Debug: Check pagination data
    if (actualPagination) {
        console.log('Sessions Pagination Debug:', {
            total: actualPagination.total,
            last_page: actualPagination.last_page,
            current_page: actualPagination.current_page,
            per_page: actualPagination.per_page,
            links_count: actualPagination.links?.length || 0,
            shouldShow: actualPagination.total > 0 && actualPagination.last_page > 1,
        });
        
        // Log warning if pagination should show but doesn't
        if (actualPagination.total > actualPagination.per_page && actualPagination.last_page === 1) {
            console.warn('⚠️ WARNING: Total sessions (' + actualPagination.total + ') > per_page (' + actualPagination.per_page + ') but last_page is 1. This indicates a pagination calculation issue.');
        }
    } else {
        console.log('Sessions Pagination: pagination prop is missing or undefined');
        console.log('Available pageProps keys:', Object.keys(pageProps));
    }

    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
    const [isDeleteAllModalOpen, setIsDeleteAllModalOpen] = useState(false);
    const [selectedSession, setSelectedSession] = useState<Session | null>(null);
    const [selectedUser, setSelectedUser] = useState<{ id: number; name: string } | null>(null);

    const handleDelete = (session: Session) => {
        setSelectedSession(session);
        setIsDeleteModalOpen(true);
    };

    const handleDeleteAll = (userId: number, userName: string) => {
        setSelectedUser({ id: userId, name: userName });
        setIsDeleteAllModalOpen(true);
    };

    const handleDeleteConfirm = () => {
        if (selectedSession) {
            router.delete(`/admin/sessions/${selectedSession.id}`, {
                onSuccess: () => {
                    setIsDeleteModalOpen(false);
                    setSelectedSession(null);
                },
            });
        }
    };

    const handleDeleteAllConfirm = () => {
        if (selectedUser) {
            router.delete(`/admin/sessions/user/${selectedUser.id}`, {
                onSuccess: () => {
                    setIsDeleteAllModalOpen(false);
                    setSelectedUser(null);
                },
            });
        }
    };

    const getRoleBadge = (role: string) => {
        const roleClasses = {
            admin: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
            partner: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
            user: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',
        };

        return (
            <span
                className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${
                    roleClasses[role as keyof typeof roleClasses] || roleClasses.user
                }`}
            >
                {role.charAt(0).toUpperCase() + role.slice(1)}
            </span>
        );
    };

    const getTimeAgo = (timestamp: number) => {
        const now = Math.floor(Date.now() / 1000);
        const diff = now - timestamp;

        if (diff < 60) {
            return 'Baru saja';
        }
        if (diff < 3600) {
            const minutes = Math.floor(diff / 60);
            return `${minutes} menit yang lalu`;
        }
        if (diff < 86400) {
            const hours = Math.floor(diff / 3600);
            return `${hours} jam yang lalu`;
        }
        const days = Math.floor(diff / 86400);
        return `${days} hari yang lalu`;
    };

    // Group sessions by user
    const sessionsByUser = sessions.reduce((acc, session) => {
        if (!acc[session.user_id]) {
            acc[session.user_id] = {
                user_id: session.user_id,
                user_name: session.user_name,
                user_email: session.user_email,
                user_role: session.user_role,
                sessions: [],
            };
        }
        acc[session.user_id].sessions.push(session);
        return acc;
    }, {} as Record<number, { user_id: number; user_name: string; user_email: string; user_role: string; sessions: Session[] }>);

    return (
        <AdminLayout title="Sessions Management">
            <Head title="Sessions Management" />
            <div className="space-y-6">
                {/* Header dengan Refresh Button */}
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">Sessions Management</h2>
                        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                            Kelola dan monitor semua session aktif dari users
                        </p>
                    </div>
                    <RefreshButton />
                </div>

                {/* Stats */}
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                    <Card padding="md">
                        <div className="text-sm font-medium text-gray-500 dark:text-gray-400">Total Sessions</div>
                        <div className="mt-2 text-2xl font-bold text-gray-900 dark:text-white">
                            {sessions.length}
                        </div>
                    </Card>
                    <Card padding="md">
                        <div className="text-sm font-medium text-gray-500 dark:text-gray-400">Active Users</div>
                        <div className="mt-2 text-2xl font-bold text-gray-900 dark:text-white">
                            {Object.keys(sessionsByUser).length}
                        </div>
                    </Card>
                    <Card padding="md">
                        <div className="text-sm font-medium text-gray-500 dark:text-gray-400">User Sessions</div>
                        <div className="mt-2 text-2xl font-bold text-gray-900 dark:text-white">
                            {sessions.filter((s) => s.user_role === 'user').length}
                        </div>
                    </Card>
                </div>

                {/* Sessions Table */}
                <Card padding="none">
                    <Table pagination={actualPagination}>
                        <TableHeader>
                            <TableHeaderCell>User</TableHeaderCell>
                            <TableHeaderCell>Role</TableHeaderCell>
                            <TableHeaderCell>IP Address</TableHeaderCell>
                            <TableHeaderCell>Browser/Device</TableHeaderCell>
                            <TableHeaderCell>Last Activity</TableHeaderCell>
                            <TableHeaderCell className="text-right">Actions</TableHeaderCell>
                        </TableHeader>
                        <TableBody>
                            {sessions.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={6} className="text-center py-8 text-gray-500 dark:text-gray-400">
                                        Tidak ada session aktif
                                    </TableCell>
                                </TableRow>
                            ) : (
                                sessions.map((session) => (
                                    <TableRow key={session.id}>
                                        <TableCell>
                                            <div>
                                                <div className="font-medium text-gray-900 dark:text-white">
                                                    {session.user_name}
                                                </div>
                                                <div className="text-sm text-gray-500 dark:text-gray-400">
                                                    {session.user_email}
                                                </div>
                                            </div>
                                        </TableCell>
                                        <TableCell>{getRoleBadge(session.user_role)}</TableCell>
                                        <TableCell className="font-mono text-sm">{session.ip_address}</TableCell>
                                        <TableCell className="text-sm">{session.user_agent}</TableCell>
                                        <TableCell>
                                            <div className="text-sm">
                                                <div className="text-gray-900 dark:text-white">
                                                    {new Date(session.last_activity).toLocaleString('id-ID')}
                                                </div>
                                                <div className="text-gray-500 dark:text-gray-400">
                                                    {getTimeAgo(session.last_activity_timestamp)}
                                                </div>
                                            </div>
                                        </TableCell>
                                        <TableCell>
                                            <div className="flex items-center justify-end gap-2">
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() => handleDeleteAll(session.user_id, session.user_name)}
                                                >
                                                    Hapus Semua
                                                </Button>
                                                <Button variant="danger" size="sm" onClick={() => handleDelete(session)}>
                                                    Hapus
                                                </Button>
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </Card>

                {/* Delete Session Modal */}
                <Modal
                    isOpen={isDeleteModalOpen}
                    onClose={() => {
                        setIsDeleteModalOpen(false);
                        setSelectedSession(null);
                    }}
                    title="Hapus Session"
                    size="sm"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => {
                                    setIsDeleteModalOpen(false);
                                    setSelectedSession(null);
                                }}
                            >
                                Batal
                            </Button>
                            <Button variant="danger" onClick={handleDeleteConfirm}>
                                Hapus
                            </Button>
                        </div>
                    }
                >
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                        Apakah Anda yakin ingin menghapus session ini? User akan ter-logout dari perangkat ini.
                    </p>
                    {selectedSession && (
                        <div className="mt-4 rounded-lg bg-gray-50 p-3 dark:bg-gray-700/50">
                            <div className="text-sm">
                                <div className="font-medium text-gray-900 dark:text-white">
                                    {selectedSession.user_name}
                                </div>
                                <div className="text-gray-500 dark:text-gray-400">{selectedSession.user_email}</div>
                                <div className="mt-2 text-gray-500 dark:text-gray-400">
                                    IP: {selectedSession.ip_address}
                                </div>
                            </div>
                        </div>
                    )}
                </Modal>

                {/* Delete All Sessions Modal */}
                <Modal
                    isOpen={isDeleteAllModalOpen}
                    onClose={() => {
                        setIsDeleteAllModalOpen(false);
                        setSelectedUser(null);
                    }}
                    title="Hapus Semua Session"
                    size="sm"
                    footer={
                        <div className="flex justify-end gap-2">
                            <Button
                                variant="secondary"
                                onClick={() => {
                                    setIsDeleteAllModalOpen(false);
                                    setSelectedUser(null);
                                }}
                            >
                                Batal
                            </Button>
                            <Button variant="danger" onClick={handleDeleteAllConfirm}>
                                Hapus Semua
                            </Button>
                        </div>
                    }
                >
                    <p className="text-sm text-gray-600 dark:text-gray-400">
                        Apakah Anda yakin ingin menghapus semua session untuk user ini? User akan ter-logout dari
                        semua perangkat.
                    </p>
                    {selectedUser && (
                        <div className="mt-4 rounded-lg bg-gray-50 p-3 dark:bg-gray-700/50">
                            <div className="text-sm font-medium text-gray-900 dark:text-white">
                                {selectedUser.name}
                            </div>
                        </div>
                    )}
                </Modal>
            </div>
        </AdminLayout>
    );
}

