import React from "react";
import { ArrowUp, ArrowDown, Clock, User, DocumentText } from "iconsax-react";
import Button from "../../../components/Button";
import StatusCircle from "../../../components/StatusCircle";
import Td from "../../../components/Td";
import {
    AccessLog,
    OperationType,
    UserType,
    OperationTypeLabels,
    UserTypeLabels,
} from "../types/AccessLogTypes";

interface AccessLogsTableProps {
    logs: AccessLog[];
    loading: boolean;
    onViewDetails: (log: AccessLog) => void;
    onSort: (field: string, order: "ASC" | "DESC") => void;
    sortBy?: string;
    sortOrder?: "ASC" | "DESC";
}

const AccessLogsTable: React.FC<AccessLogsTableProps> = ({
    logs,
    loading,
    onViewDetails,
    onSort,
    sortBy,
    sortOrder,
}) => {
    const getOperationTypeColor = (type: OperationType): string => {
        const colors = {
            CREATE: "green",
            UPDATE: "blue",
            DELETE: "red",
            READ: "gray",
            LOGIN: "purple",
            LOGOUT: "orange",
            APPROVE: "green",
            REJECT: "red",
            ACTIVATE: "green",
            DEACTIVATE: "red",
            EXPORT: "blue",
            IMPORT: "blue",
            BULK_UPDATE: "blue",
            BULK_DELETE: "red",
        };
        return colors[type as keyof typeof colors] || "gray";
    };

    const getUserTypeBadgeColor = (type: UserType): string => {
        const colors = {
            SYSTEM: "bg-gray-100 text-gray-800",
            ADMIN: "bg-red-100 text-red-800",
            USER: "bg-blue-100 text-blue-800",
        };
        return colors[type as keyof typeof colors] || "bg-gray-100 text-gray-800";
    };

    const getStatusColor = (statusCode?: number): string => {
        if (!statusCode) return "bg-gray-100 text-gray-800";
        if (statusCode >= 200 && statusCode < 300) return "bg-green-100 text-green-800";
        if (statusCode >= 400 && statusCode < 500) return "bg-yellow-100 text-yellow-800";
        if (statusCode >= 500) return "bg-red-100 text-red-800";
        return "bg-gray-100 text-gray-800";
    };

    const formatDate = (dateString: string): string => {
        const date = new Date(dateString);
        return new Intl.DateTimeFormat("fa-IR", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
        }).format(date);
    };

    const formatExecutionTime = (time?: number): string => {
        if (!time) return "-";
        if (time < 1000) return `${time}ms`;
        return `${(time / 1000).toFixed(2)}s`;
    };

    const renderSortButton = (field: string, label: string) => (
        <button
            className="flex items-center gap-1 text-xs font-medium text-gray-500 hover:text-gray-700"
            onClick={() => {
                const newOrder = sortBy === field && sortOrder === "ASC" ? "DESC" : "ASC";
                onSort(field, newOrder);
            }}
        >
            {label}
            {sortBy === field ? (
                sortOrder === "ASC" ? (
                    <ArrowUp size={14} />
                ) : (
                    <ArrowDown size={14} />
                )
            ) : (
                <div className="w-3.5 h-3.5" />
            )}
        </button>
    );

    if (loading) {
        return (
            <div className='relative overflow-x-auto rounded-3xl mt-9 w-full'>
                <div className="p-8 text-center">
                    <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
                    <p className="text-gray-600">در حال بارگذاری...</p>
                </div>
            </div>
        );
    }

    if (!logs || logs.length === 0) {
        return (
            <div className='relative overflow-x-auto rounded-3xl mt-9 w-full'>
                <div className="p-8 text-center">
                    <DocumentText size={48} className="text-gray-400 mx-auto mb-4" />
                    <p className="text-gray-600 text-lg mb-2">هیچ لاگی یافت نشد</p>
                    <p className="text-gray-500">فیلترهای خود را تغییر دهید یا دوباره تلاش کنید</p>
                </div>
            </div>
        );
    }

    return (
        <div className='relative overflow-x-auto rounded-3xl mt-9 w-full'>
            <table className='w-full text-sm'>
                <thead className='thead'>
                    <tr>
                        <Td text="">
                            {renderSortButton("createdAt", "تاریخ و زمان")}
                        </Td>
                        <Td text="نوع عملیات" />
                        <Td text="نوع کاربر" />
                        <Td text="موجودیت" />
                        <Td text="توضیحات" />
                        <Td text="کاربر" />
                        <Td text="IP" />
                        <Td text="وضعیت" />
                        <Td text="زمان اجرا" />
                        <Td text="عملیات" />
                    </tr>
                </thead>
                <tbody>
                    {logs.map((log) => (
                        <tr key={log.id} className='tr'>
                            <Td text="">
                                <div className="flex items-center gap-2">
                                    <Clock size={16} className="text-gray-400" />
                                    {formatDate(log.createdAt)}
                                </div>
                            </Td>

                            <Td text="">
                                <StatusCircle
                                    color={getOperationTypeColor(log.operationType)}
                                    text={OperationTypeLabels[log.operationType]}
                                />
                            </Td>

                            <Td text="">
                                <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getUserTypeBadgeColor(log.userType)}`}>
                                    {UserTypeLabels[log.userType]}
                                </span>
                            </Td>

                            <Td text="">
                                <div>
                                    <div className="font-medium">{log.entityName}</div>
                                    {log.entityId && (
                                        <div className="text-xs text-gray-500 truncate max-w-[100px]">
                                            {log.entityId}
                                        </div>
                                    )}
                                </div>
                            </Td>

                            <Td text="">
                                <div className="truncate max-w-xs" title={log.actionDescription}>
                                    {log.actionDescription || "-"}
                                </div>
                            </Td>

                            <Td text="">
                                {log.user ? (
                                    <div className="flex items-center gap-2">
                                        <User size={16} className="text-gray-400" />
                                        <div>
                                            <div className="font-medium">
                                                {log.user.firstName} {log.user.lastName}
                                            </div>
                                            <div className="text-xs text-gray-500">
                                                {log.user.email}
                                            </div>
                                        </div>
                                    </div>
                                ) : (
                                    <span className="text-gray-500">سیستم</span>
                                )}
                            </Td>

                            <Td text={log.ipAddress || "-"} />

                            <Td text="">
                                <div>
                                    <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getStatusColor(log.statusCode)}`}>
                                        {log.statusCode || "N/A"}
                                    </span>
                                    {log.errorMessage && (
                                        <div className="text-xs text-red-600 mt-1 truncate max-w-[100px]" title={log.errorMessage}>
                                            {log.errorMessage}
                                        </div>
                                    )}
                                </div>
                            </Td>

                            <Td text={formatExecutionTime(log.executionTime)} />

                            <Td text="">
                                <Button
                                    onClick={() => onViewDetails(log)}
                                    className="w-fit px-4"
                                >
                                    جزئیات
                                </Button>
                            </Td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default AccessLogsTable;
