import React from "react";
import {
    CloseSquare,
    InfoCircle,
    User,
    Clock,
    Monitor,
    Code,
    Warning2,
    DocumentText,
    Activity
} from "iconsax-react";
import DefaulModal from "../../../components/DefaulModal";
import Button from "../../../components/Button";
import StatusCircle from "../../../components/StatusCircle";
import {
    AccessLog,
    OperationType,
    UserType,
    OperationTypeLabels,
    UserTypeLabels,
    HttpMethodLabels,
} from "../types/AccessLogTypes";

interface LogDetailsModalProps {
    log: AccessLog | null;
    isOpen: boolean;
    onClose: () => void;
    loading?: boolean;
    error?: string | null;
}

const LogDetailsModal: React.FC<LogDetailsModalProps> = ({
    log,
    isOpen,
    onClose,
    loading = false,
    error = null,
}) => {
    if (!isOpen) return null;

    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: "long",
            day: "numeric",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
        }).format(date);
    };

    const formatExecutionTime = (time?: number): string => {
        if (!time) return "-";
        if (time < 1000) return `${time} میلی‌ثانیه`;
        return `${(time / 1000).toFixed(2)} ثانیه`;
    };

    const formatJson = (jsonString?: string): string => {
        if (!jsonString) return "";
        try {
            const parsed = JSON.parse(jsonString);
            return JSON.stringify(parsed, null, 2);
        } catch {
            return jsonString;
        }
    };

    const InfoRow: React.FC<{
        icon: React.ReactNode;
        label: string;
        value: React.ReactNode;
        fullWidth?: boolean;
    }> = ({ icon, label, value, fullWidth = false }) => (
        <div className={`${fullWidth ? "col-span-2" : ""}`}>
            <div className="flex items-start gap-3 p-3 bg-gray-50 rounded-lg">
                <div className="flex-shrink-0 mt-0.5 text-gray-600">
                    {icon}
                </div>
                <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 mb-1">{label}</p>
                    <div className="text-sm text-gray-700">{value}</div>
                </div>
            </div>
        </div>
    );

    const CodeBlock: React.FC<{ title: string; content?: string }> = ({ title, content }) => {
        if (!content) return null;

        return (
            <div className="mt-6">
                <h4 className="text-sm font-medium text-gray-900 mb-3 flex items-center gap-2">
                    <Code size={16} />
                    {title}
                </h4>
                <div className="bg-gray-900 rounded-lg p-4 overflow-x-auto">
                    <pre className="text-sm text-green-400 whitespace-pre-wrap font-mono">
                        {formatJson(content)}
                    </pre>
                </div>
            </div>
        );
    };

    return (
        <DefaulModal open={isOpen} close={onClose} width={800}>
            <div className="p-6">
                {/* Header */}
                <div className="flex items-center justify-between mb-6">
                    <div className="flex items-center gap-3">
                        <InfoCircle size={24} className="text-blue-600" />
                        <h2 className="text-xl font-bold text-gray-900">جزئیات لاگ</h2>
                    </div>
                    <Button
                        onClick={onClose}
                        className="text-sm px-3 py-1 bg-transparent text-gray-400 hover:text-gray-600"
                    >
                        <CloseSquare size={20} />
                    </Button>
                </div>

                {/* Loading State */}
                {loading && (
                    <div className="flex items-center justify-center py-12">
                        <div className="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>
                )}

                {/* Error State */}
                {error && (
                    <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
                        <div className="flex items-center gap-3">
                            <Warning2 size={20} className="text-red-600" />
                            <div>
                                <h3 className="text-sm font-medium text-red-900">خطا در بارگذاری</h3>
                                <p className="text-sm text-red-700 mt-1">{error}</p>
                            </div>
                        </div>
                    </div>
                )}

                {/* Content - Only show if not loading and no error */}
                {!loading && !error && log && (
                    <>
                        {/* Basic Information */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                            <InfoRow
                                icon={<Activity size={18} />}
                                label="نوع عملیات"
                                value={
                                    <StatusCircle
                                        color={getOperationTypeColor(log.operationType)}
                                        text={OperationTypeLabels[log.operationType]}
                                    />
                                }
                            />

                            <InfoRow
                                icon={<User size={18} />}
                                label="نوع کاربر"
                                value={
                                    <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getUserTypeBadgeColor(log.userType)}`}>
                                        {UserTypeLabels[log.userType]}
                                    </span>
                                }
                            />

                            <InfoRow
                                icon={<DocumentText size={18} />}
                                label="موجودیت"
                                value={
                                    <div>
                                        <div className="font-medium">{log.entityName}</div>
                                        {log.entityId && (
                                            <div className="text-xs text-gray-500 mt-1">{log.entityId}</div>
                                        )}
                                    </div>
                                }
                            />

                            <InfoRow
                                icon={<Clock size={18} />}
                                label="تاریخ و زمان"
                                value={formatDate(log.createdAt)}
                            />

                            {log.actionDescription && (
                                <InfoRow
                                    icon={<InfoCircle size={18} />}
                                    label="توضیحات عملیات"
                                    value={log.actionDescription}
                                    fullWidth
                                />
                            )}
                        </div>

                        {/* User Information */}
                        {log.user && (
                            <div className="mb-6">
                                <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center gap-2">
                                    <User size={18} />
                                    اطلاعات کاربر
                                </h3>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <InfoRow
                                        icon={<User size={18} />}
                                        label="نام و نام خانوادگی"
                                        value={`${log.user.firstName} ${log.user.lastName}`}
                                    />
                                    <InfoRow
                                        icon={<InfoCircle size={18} />}
                                        label="ایمیل"
                                        value={log.user.email}
                                    />
                                    {log.user.phone && (
                                        <InfoRow
                                            icon={<InfoCircle size={18} />}
                                            label="شماره تماس"
                                            value={log.user.phone}
                                        />
                                    )}
                                    <InfoRow
                                        icon={<InfoCircle size={18} />}
                                        label="شناسه کاربر"
                                        value={log.user.id}
                                    />
                                </div>
                            </div>
                        )}

                        {/* Technical Details */}
                        <div className="mb-6">
                            <h3 className="text-lg font-semibold text-gray-900 mb-3 flex items-center gap-2">
                                <Monitor size={18} />
                                جزئیات فنی
                            </h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {log.ipAddress && (
                                    <InfoRow
                                        icon={<Monitor size={18} />}
                                        label="آدرس IP"
                                        value={log.ipAddress}
                                    />
                                )}

                                {log.endpoint && (
                                    <InfoRow
                                        icon={<Code size={18} />}
                                        label="Endpoint"
                                        value={log.endpoint}
                                    />
                                )}

                                {log.httpMethod && (
                                    <InfoRow
                                        icon={<Code size={18} />}
                                        label="متد HTTP"
                                        value={HttpMethodLabels[log.httpMethod]}
                                    />
                                )}

                                <InfoRow
                                    icon={<InfoCircle size={18} />}
                                    label="کد وضعیت"
                                    value={
                                        <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getStatusColor(log.statusCode)}`}>
                                            {log.statusCode || "N/A"}
                                        </span>
                                    }
                                />

                                {log.executionTime && (
                                    <InfoRow
                                        icon={<Clock size={18} />}
                                        label="زمان اجرا"
                                        value={formatExecutionTime(log.executionTime)}
                                    />
                                )}

                                {log.sessionId && (
                                    <InfoRow
                                        icon={<InfoCircle size={18} />}
                                        label="شناسه جلسه"
                                        value={log.sessionId}
                                    />
                                )}

                                {log.requestId && (
                                    <InfoRow
                                        icon={<InfoCircle size={18} />}
                                        label="شناسه درخواست"
                                        value={log.requestId}
                                    />
                                )}
                            </div>
                        </div>

                        {/* Error Information */}
                        {log.errorMessage && (
                            <div className="mb-6">
                                <h3 className="text-lg font-semibold text-red-600 mb-3 flex items-center gap-2">
                                    <Warning2 size={18} />
                                    اطلاعات خطا
                                </h3>
                                <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                                    <p className="text-red-800">{log.errorMessage}</p>
                                </div>
                            </div>
                        )}

                        {/* User Agent */}
                        {log.userAgent && (
                            <InfoRow
                                icon={<Monitor size={18} />}
                                label="User Agent"
                                value={
                                    <div className="text-xs font-mono bg-gray-100 p-2 rounded break-all">
                                        {log.userAgent}
                                    </div>
                                }
                                fullWidth
                            />
                        )}

                        {/* Data Changes */}
                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <CodeBlock title="مقادیر قبلی" content={log.oldValues} />
                            <CodeBlock title="مقادیر جدید" content={log.newValues} />
                        </div>

                        {/* Metadata */}
                        {log.metadata && Object.keys(log.metadata).length > 0 && (
                            <CodeBlock
                                title="متادیتا"
                                content={JSON.stringify(log.metadata, null, 2)}
                            />
                        )}

                        {/* Footer */}
                        <div className="flex justify-end mt-8 pt-6 border-t border-gray-200">
                            <Button
                                onClick={onClose}
                                className="bg-blue-600 text-white hover:bg-blue-700"
                            >
                                بستن
                            </Button>
                        </div>
                    </>
                )}

                {/* No Data State */}
                {!loading && !error && !log && (
                    <div className="text-center py-12">
                        <InfoCircle size={48} className="text-gray-400 mx-auto mb-4" />
                        <p className="text-gray-600">هیچ داده‌ای برای نمایش وجود ندارد</p>
                    </div>
                )}
            </div>
        </DefaulModal>
    );
};

export default LogDetailsModal;
