import { Head, router, Link } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import AdminLayout from '@/components/Layouts/AdminLayout';
import Card from '@/components/Card/Card';
import Table, { TableBody, TableCell, TableHeader, TableHeaderCell, TableRow } from '@/components/Table/Table';
import SearchInput from '@/components/SearchInput/SearchInput';
import RefreshButton from '@/components/RefreshButton/RefreshButton';
import Select from '@/components/Select/Select';
import Input from '@/components/Input/Input';
import { ActivityLog, User } from '@/types';

interface ActivityLogsPageProps {
    logs: ActivityLog[];
    pagination?: {
        data: ActivityLog[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
        links: Array<{ url: string | null; label: string; active: boolean }>;
    };
    actions: string[];
    modelTypes: string[];
    filters?: {
        action?: string;
        user_id?: string;
        model_type?: string;
        search?: string;
        date_from?: string;
        date_to?: string;
    };
}

export default function Index({ logs, pagination, actions, modelTypes, filters = {} }: ActivityLogsPageProps) {
    const [search, setSearch] = useState(filters.search || '');
    const [actionFilter, setActionFilter] = useState(filters.action || 'all');
    const [modelTypeFilter, setModelTypeFilter] = useState(filters.model_type || 'all');
    const [dateFrom, setDateFrom] = useState(filters.date_from || '');
    const [dateTo, setDateTo] = useState(filters.date_to || '');

    // Handle search dengan debounce
    useEffect(() => {
        const isInitialLoad =
            search === (filters.search || '') &&
            actionFilter === (filters.action || 'all') &&
            modelTypeFilter === (filters.model_type || 'all') &&
            dateFrom === (filters.date_from || '') &&
            dateTo === (filters.date_to || '');
        if (isInitialLoad) {
            return;
        }

        const timer = setTimeout(() => {
            router.get(
                '/admin/activity-logs',
                {
                    action: actionFilter !== 'all' ? actionFilter : undefined,
                    model_type: modelTypeFilter !== 'all' ? modelTypeFilter : undefined,
                    search: search || undefined,
                    date_from: dateFrom || undefined,
                    date_to: dateTo || undefined,
                },
                {
                    preserveState: true,
                    preserveScroll: true,
                    replace: true,
                }
            );
        }, 300);

        return () => clearTimeout(timer);
    }, [search, actionFilter, modelTypeFilter, dateFrom, dateTo]);

    const handleFilterChange = () => {
        router.get(
            '/admin/activity-logs',
            {
                action: actionFilter !== 'all' ? actionFilter : undefined,
                model_type: modelTypeFilter !== 'all' ? modelTypeFilter : undefined,
                search: search || undefined,
                date_from: dateFrom || undefined,
                date_to: dateTo || undefined,
            },
            {
                preserveState: true,
                preserveScroll: true,
                replace: true,
            }
        );
    };

    const handleSearchClear = () => {
        setSearch('');
    };

    const getActionBadge = (action: string) => {
        const actionClasses: Record<string, string> = {
            login: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
            logout: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',
            create: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
            update: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
            delete: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
            view: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400',
        };

        return (
            <span
                className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${
                    actionClasses[action] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
                }`}
            >
                {action.charAt(0).toUpperCase() + action.slice(1)}
            </span>
        );
    };

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleString('id-ID', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        });
    };

    const getModelTypeName = (modelType?: string) => {
        if (!modelType) return '-';
        return modelType.split('\\').pop() || modelType;
    };

    return (
        <AdminLayout title="Activity Logs">
            <Head title="Activity Logs" />
            <div className="space-y-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-bold text-gray-900 dark:text-white">Activity Logs</h2>
                        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                            Riwayat aktivitas semua user, partner, dan admin
                        </p>
                    </div>
                    <RefreshButton />
                </div>

                {/* Filters */}
                <Card padding="md">
                    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-5">
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Cari
                            </label>
                            <SearchInput
                                placeholder="Cari berdasarkan deskripsi..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                onClear={handleSearchClear}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Filter Action
                            </label>
                            <Select
                                value={actionFilter}
                                onChange={(e) => {
                                    setActionFilter(e.target.value);
                                    handleFilterChange();
                                }}
                                options={[
                                    { value: 'all', label: 'Semua Action' },
                                    ...actions.map((action) => ({
                                        value: action,
                                        label: action.charAt(0).toUpperCase() + action.slice(1),
                                    })),
                                ]}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Filter Model Type
                            </label>
                            <Select
                                value={modelTypeFilter}
                                onChange={(e) => {
                                    setModelTypeFilter(e.target.value);
                                    handleFilterChange();
                                }}
                                options={[
                                    { value: 'all', label: 'Semua Model' },
                                    ...modelTypes.map((type) => ({
                                        value: type,
                                        label: getModelTypeName(type),
                                    })),
                                ]}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Dari Tanggal
                            </label>
                            <Input
                                type="date"
                                value={dateFrom}
                                onChange={(e) => {
                                    setDateFrom(e.target.value);
                                    handleFilterChange();
                                }}
                            />
                        </div>
                        <div>
                            <label className="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Sampai Tanggal
                            </label>
                            <Input
                                type="date"
                                value={dateTo}
                                onChange={(e) => {
                                    setDateTo(e.target.value);
                                    handleFilterChange();
                                }}
                            />
                        </div>
                    </div>
                </Card>

                {/* Table */}
                <Card padding="none">
                    <Table pagination={pagination}>
                        <TableHeader>
                            <TableHeaderCell>Waktu</TableHeaderCell>
                            <TableHeaderCell>User</TableHeaderCell>
                            <TableHeaderCell>Action</TableHeaderCell>
                            <TableHeaderCell>Deskripsi</TableHeaderCell>
                            <TableHeaderCell>Model</TableHeaderCell>
                            <TableHeaderCell>IP Address</TableHeaderCell>
                        </TableHeader>
                        <TableBody>
                            {!logs || logs.length === 0 ? (
                                <TableRow>
                                    <TableCell colSpan={6} className="text-center py-8 text-gray-500 dark:text-gray-400">
                                        Tidak ada data activity log
                                    </TableCell>
                                </TableRow>
                            ) : (
                                logs.map((log) => (
                                    <TableRow key={log.id}>
                                        <TableCell className="text-sm">{formatDate(log.created_at)}</TableCell>
                                        <TableCell>
                                            {log.user ? (
                                                <div>
                                                    <div className="font-medium text-gray-900 dark:text-white">
                                                        {log.user.name}
                                                    </div>
                                                    <div className="text-xs text-gray-500 dark:text-gray-400">
                                                        {log.user.email}
                                                    </div>
                                                </div>
                                            ) : (
                                                <span className="text-gray-400 dark:text-gray-500">System</span>
                                            )}
                                        </TableCell>
                                        <TableCell>{getActionBadge(log.action)}</TableCell>
                                        <TableCell className="max-w-xs truncate">{log.description || '-'}</TableCell>
                                        <TableCell>
                                            {log.model_type ? (
                                                <div>
                                                    <div className="text-sm font-medium">
                                                        {getModelTypeName(log.model_type)}
                                                    </div>
                                                    {log.model_id && (
                                                        <div className="text-xs text-gray-500 dark:text-gray-400">
                                                            ID: {log.model_id}
                                                        </div>
                                                    )}
                                                </div>
                                            ) : (
                                                '-'
                                            )}
                                        </TableCell>
                                        <TableCell className="text-sm font-mono">{log.ip_address || '-'}</TableCell>
                                    </TableRow>
                                ))
                            )}
                        </TableBody>
                    </Table>
                </Card>
            </div>
        </AdminLayout>
    );
}

