import { useState, useEffect, useCallback } from 'react'
import Navbar from '../components/common/Navbar'
import Button from '../components/common/Button'
import Badge from '../components/common/Badge'
import { activityLogsAPI } from '../api/endpoints'
import debounce from 'lodash.debounce'
import ViewLogModal from '../components/ViewLogModal'
import { IoSearchOutline, IoRefreshOutline, IoFunnelOutline, IoEyeOutline } from 'react-icons/io5'

// Brand palette
const TEAL = '#409CA4'
const GREEN = '#5cb85c'
const ORANGE = '#e8713a'

const getLogBadgeVariant = (logType) => {
    if (logType?.includes('failed') || logType?.includes('error')) return 'danger'
    if (logType?.includes('login')) return 'success'
    if (logType?.includes('delete')) return 'warning'
    return 'info'
}

const ActivityLogs = () => {
    const [logs, setLogs] = useState([])
    const [loading, setLoading] = useState(false)
    const [totalPages, setTotalPages] = useState(1)
    const [currentPage, setCurrentPage] = useState(1)
    const [limit, setLimit] = useState(20)
    const [totalLogs, setTotalLogs] = useState(0)

    const [selectedLog, setSelectedLog] = useState(null)
    const [isViewModalOpen, setIsViewModalOpen] = useState(false)

    const [searchTerm, setSearchTerm] = useState('')
    const [search, setSearch] = useState('')
    const [logTypes, setLogTypes] = useState([])
    const [selectedType, setSelectedType] = useState('')

    useEffect(() => {
        const fetchTypes = async () => {
            try {
                const res = await activityLogsAPI.getTypes()
                setLogTypes(res.data.data || [])
            } catch (e) {
                console.error(e)
            }
        }
        fetchTypes()
    }, [])

    const fetchLogs = useCallback(async (page = 1, searchEmail = '', type = '') => {
        setLoading(true)
        try {
            const response = await activityLogsAPI.getLogs(page, limit, searchEmail, type)
            setLogs(response.data.data || [])
            const pagination = response.data.pagination || {}
            setCurrentPage(pagination.page || 1)
            setTotalPages(pagination.pages || 1)
            setTotalLogs(pagination.total || 0)
        } catch (error) {
            console.error(error)
        } finally {
            setLoading(false)
        }
    }, [limit])

    const debouncedSearch = useCallback(
        debounce((value) => {
            setSearch(value)
            setCurrentPage(1)
        }, 500),
        []
    )

    const handleSearch = (e) => {
        setSearchTerm(e.target.value)
        debouncedSearch(e.target.value)
    }

    const handleViewLog = (log) => {
        setSelectedLog(log)
        setIsViewModalOpen(true)
    }

    useEffect(() => {
        fetchLogs(currentPage, search, selectedType)
    }, [currentPage, search, selectedType, limit, fetchLogs])

    const goToPage = (p) => {
        const page = Math.max(1, Math.min(totalPages, p))
        setCurrentPage(page)
    }

    const pageNumbers = () => {
        const pages = []
        const delta = 2
        for (let i = Math.max(1, currentPage - delta); i <= Math.min(totalPages, currentPage + delta); i++) {
            pages.push(i)
        }
        return pages
    }

    return (
        <div className="space-y-6 pb-10">
            <Navbar title="Activity Logs" subtitle="Monitor all system events and user activities" />

            {/* ── DataTables-style Panel ── */}
            <div className="bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden">

                {/* Panel Header */}
                <div
                    className="px-6 py-5 flex flex-col md:flex-row md:items-center justify-between gap-4"
                    style={{ borderBottom: `3px solid ${TEAL}`, background: 'linear-gradient(to right,#f0fafa,#fff)' }}
                >
                    <div>
                        <h2 className="text-xl font-black text-[#111827] flex items-center gap-2">
                            <IoRefreshOutline style={{ color: TEAL }} /> System Activity
                        </h2>
                        <p className="text-sm font-bold text-gray-500 mt-1">
                            Total <strong style={{ color: TEAL }}>{totalLogs}</strong> log entries recorded
                        </p>
                    </div>
                    {/* Badge summary */}
                    <div className="flex gap-3 flex-wrap">
                        <Badge variant="success" size="sm">✓ Logins</Badge>
                        <Badge variant="danger" size="sm">✕ Errors</Badge>
                        <Badge variant="info" size="sm">ℹ General</Badge>
                    </div>
                </div>

                {/* ── Filters Row ── */}
                <div className="px-6 py-5 bg-gray-50 border-b border-gray-100">
                    <div className="flex flex-col lg:flex-row gap-4 items-start lg:items-center">

                        {/* Search */}
                        <div className="relative flex-1 min-w-[300px]">
                            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400">
                                <IoSearchOutline size={22} />
                            </span>
                            <input
                                type="text"
                                placeholder="Search by email or user identity…"
                                value={searchTerm}
                                onChange={handleSearch}
                                className="w-full pl-12 pr-4 py-3 text-base bg-white border-2 border-gray-200 rounded-xl outline-none focus:border-[#409CA4] font-black text-[#111827]"
                            />
                        </div>

                        <div className="flex flex-wrap items-center gap-3">
                            <select
                                value={selectedType}
                                onChange={e => { setSelectedType(e.target.value); setCurrentPage(1) }}
                                className="px-4 py-3 border-2 border-gray-200 rounded-xl bg-white text-[#111827] font-black text-sm outline-none focus:border-[#409CA4] cursor-pointer"
                            >
                                <option value="">📋 All Log Types</option>
                                {logTypes.map(t => (
                                    <option key={t} value={t}>{t}</option>
                                ))}
                            </select>

                            <select
                                value={limit}
                                onChange={e => { setLimit(Number(e.target.value)); setCurrentPage(1) }}
                                className="px-4 py-3 border-2 border-gray-200 rounded-xl bg-white text-[#111827] font-black text-sm outline-none focus:border-[#409CA4] cursor-pointer"
                            >
                                <option value={10}>Show: 10</option>
                                <option value={20}>Show: 20</option>
                                <option value={50}>Show: 50</option>
                                <option value={100}>Show: 100</option>
                            </select>

                            <Button
                                onClick={() => { setSearchTerm(''); setSearch(''); setSelectedType(''); setCurrentPage(1) }}
                                variant="outline"
                                size="sm"
                                className="border-gray-300 text-gray-500 hover:text-red-600 hover:border-red-200"
                            >
                                Clear
                            </Button>
                        </div>
                    </div>
                </div>

                {/* ── Table ── */}
                <div className="overflow-x-auto">
                    {loading ? (
                        <div className="flex flex-col items-center justify-center py-24 gap-4">
                            <IoRefreshOutline size={48} className="text-[#409CA4] animate-spin" />
                            <p className="text-lg font-black text-gray-400 uppercase tracking-widest">Loading History...</p>
                        </div>
                    ) : logs.length > 0 ? (
                        <table className="w-full text-left border-collapse">
                            <thead>
                                <tr style={{ backgroundColor: TEAL }}>
                                    <th className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider">ID</th>
                                    <th className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider">User Account</th>
                                    <th className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider text-center">Event Type</th>
                                    <th className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider">Log Message</th>
                                    <th className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider">Timestamp</th>
                                    <th className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                                {logs.map((log, idx) => (
                                    <tr
                                        key={log.id}
                                        style={{ backgroundColor: idx % 2 === 0 ? '#fff' : '#f8fbfc' }}
                                        className="hover:bg-[#409CA4]/5 transition-colors group"
                                    >
                                        <td className="px-6 py-5 font-mono text-xs text-gray-400">#{log.id}</td>
                                        <td className="px-6 py-5">
                                            <p className="font-black text-lg text-[#111827] leading-tight">
                                                {log.first_name ? `${log.first_name} ${log.last_name || ''}` : 'System / Guest'}
                                            </p>
                                            <p className="text-sm font-bold text-gray-500 mt-1">{log.email || 'No email associated'}</p>
                                        </td>
                                        <td className="px-6 py-5 text-center">
                                            <Badge variant={getLogBadgeVariant(log.log_type)} size="sm">
                                                {log.log_type}
                                            </Badge>
                                        </td>
                                        <td className="px-6 py-5 text-[#111827] font-bold">
                                            <span className="line-clamp-1 max-w-md" title={log.logmessage}>{log.logmessage || '—'}</span>
                                        </td>
                                        <td className="px-6 py-5">
                                            <p className="text-base font-black text-gray-700">
                                                {new Date(log.created).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}
                                            </p>
                                            <p className="text-[11px] font-bold text-gray-400 uppercase">
                                                {new Date(log.created).toLocaleTimeString()}
                                            </p>
                                        </td>
                                        <td className="px-6 py-5">
                                            <div className="flex justify-end">
                                                <button
                                                    onClick={() => handleViewLog(log)}
                                                    className="p-2.5 text-[#409CA4] hover:bg-[#409CA4]/10 rounded-xl transition-all shadow-sm bg-white border border-gray-100"
                                                >
                                                    <IoEyeOutline size={20} />
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    ) : (
                        <div className="flex flex-col items-center justify-center py-24 gap-4 text-gray-300">
                            <IoFunnelOutline size={64} className="opacity-20" />
                            <p className="font-black text-xl uppercase tracking-wider">No logs match your filters</p>
                        </div>
                    )}
                </div>

                {/* ── Pagination Footer ── */}
                {logs.length > 0 && (
                    <div
                        className="px-6 py-5 flex flex-col sm:flex-row items-center justify-between gap-4 text-sm"
                        style={{ borderTop: '2px solid #e5f0f2', backgroundColor: '#f8fbfc' }}
                    >
                        <p className="text-gray-500 font-black">
                            Showing <strong style={{ color: TEAL }}>{(currentPage - 1) * limit + 1}</strong>
                            {' '}to <strong style={{ color: TEAL }}>{Math.min(currentPage * limit, totalLogs)}</strong>
                            {' '}of <strong style={{ color: TEAL }}>{totalLogs}</strong> entries
                        </p>
                        <div className="flex items-center gap-1.5">
                            <button onClick={() => goToPage(1)} disabled={currentPage === 1}
                                className="px-4 py-2 rounded-xl text-xs font-black border-2 disabled:opacity-40 transition-all bg-white border-gray-200 text-[#409CA4] hover:border-[#409CA4]">
                                First
                            </button>
                            <button onClick={() => goToPage(currentPage - 1)} disabled={currentPage === 1}
                                className="px-4 py-2 rounded-xl text-xs font-black border-2 disabled:opacity-40 transition-all bg-white border-gray-200 text-[#409CA4] hover:border-[#409CA4]">
                                Prev
                            </button>
                            {pageNumbers().map(p => (
                                <button
                                    key={p}
                                    onClick={() => goToPage(p)}
                                    className={`px-4 py-2 rounded-xl text-xs font-black border-2 transition-all ${p === currentPage
                                            ? 'bg-[#409CA4] text-white border-[#409CA4] shadow-lg scale-110'
                                            : 'bg-white border-gray-200 text-[#409CA4] hover:border-[#409CA4]'
                                        }`}
                                >
                                    {p}
                                </button>
                            ))}
                            <button onClick={() => goToPage(currentPage + 1)} disabled={currentPage === totalPages}
                                className="px-4 py-2 rounded-xl text-xs font-black border-2 disabled:opacity-40 transition-all bg-white border-gray-200 text-[#409CA4] hover:border-[#409CA4]">
                                Next
                            </button>
                            <button onClick={() => goToPage(totalPages)} disabled={currentPage === totalPages}
                                className="px-4 py-2 rounded-xl text-xs font-black border-2 disabled:opacity-40 transition-all bg-white border-gray-200 text-[#409CA4] hover:border-[#409CA4]">
                                Last
                            </button>
                        </div>
                    </div>
                )}
            </div>

            {isViewModalOpen && (
                <ViewLogModal log={selectedLog} onClose={() => setIsViewModalOpen(false)} />
            )}
        </div>
    )
}

export default ActivityLogs
