import { useState, useEffect, useCallback } from 'react'
import { IoSearchOutline, IoAddOutline, IoTrashOutline, IoPencilOutline, IoRefreshOutline, IoNotificationsOutline } from 'react-icons/io5'
import debounce from 'lodash.debounce'
import { notificationsAPI } from '../api/endpoints'
import Button from '../components/common/Button'
import Badge from '../components/common/Badge'
import Navbar from '../components/common/Navbar'
import NotificationModal from '../components/NotificationModal'
import { toast } from 'react-hot-toast'

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

const Notifications = () => {
    const [notifications, setNotifications] = useState([])
    const [loading, setLoading] = useState(true)
    const [pagination, setPagination] = useState({ page: 1, limit: 10, total: 0, pages: 1 })
    const [filters, setFilters] = useState({
        search: '',
        startDate: '',
        endDate: '',
        filterType: 'all' // all, deleted
    })

    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        notification: null
    })

    const fetchNotifications = async (page = pagination.page, currentFilters = filters) => {
        setLoading(true)
        try {
            const response = await notificationsAPI.getAll(
                page,
                pagination.limit,
                currentFilters.search,
                currentFilters.startDate,
                currentFilters.endDate,
                currentFilters.filterType
            )
            if (response.data.success) {
                setNotifications(response.data.data)
                setPagination(response.data.pagination)
            }
        } catch (error) {
            console.error('Fetch notifications error:', error)
            toast.error('Failed to load notifications')
        } finally {
            setLoading(false)
        }
    }

    const debouncedSearch = useCallback(
        debounce((searchTerm) => {
            const newFilters = { ...filters, search: searchTerm }
            setFilters(newFilters)
            fetchNotifications(1, newFilters)
        }, 500),
        [filters]
    )

    useEffect(() => {
        fetchNotifications(1)
    }, [])

    const handleFilterChange = (name, value) => {
        const newFilters = { ...filters, [name]: value }
        setFilters(newFilters)
        fetchNotifications(1, newFilters)
    }

    const handlePageChange = (page) => {
        fetchNotifications(page)
    }

    const handleDelete = async (id) => {
        if (!window.confirm('Are you sure you want to delete this notification?')) return
        try {
            await notificationsAPI.delete(id)
            toast.success('Notification deleted successfully')
            fetchNotifications()
        } catch (error) {
            toast.error('Failed to delete notification')
        }
    }

    const handleRestore = async (id) => {
        try {
            await notificationsAPI.restore(id)
            toast.success('Notification restored successfully')
            fetchNotifications()
        } catch (error) {
            toast.error('Failed to restore notification')
        }
    }

    const handleModalSubmit = async (formData) => {
        try {
            if (modalConfig.notification) {
                await notificationsAPI.update(modalConfig.notification.id, formData)
                toast.success('Notification updated successfully')
            } else {
                await notificationsAPI.create(formData)
                toast.success('Notification created successfully')
            }
            setModalConfig({ isOpen: false, notification: null })
            fetchNotifications()
        } catch (error) {
            toast.error(error.response?.data?.message || 'Failed to save notification')
        }
    }

    const clearFilters = () => {
        const resetFilters = { search: '', startDate: '', endDate: '', filterType: 'all' }
        setFilters(resetFilters)
        fetchNotifications(1, resetFilters)
    }

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

    return (
        <div className="space-y-6 pb-10">
            <Navbar title="Notifications Management" subtitle="Create and manage system-wide announcements" />

            {/* ── 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">
                            <IoNotificationsOutline style={{ color: TEAL }} /> Notifications Center
                        </h2>
                        <p className="text-sm font-bold text-gray-500 mt-1">
                            Total <strong style={{ color: TEAL }}>{pagination.total}</strong> notifications found
                        </p>
                    </div>
                    <div className="flex items-center gap-3">
                        <Button
                            onClick={() => fetchNotifications()}
                            variant="outline"
                            size="sm"
                            className="bg-white"
                        >
                            <IoRefreshOutline className={loading ? 'animate-spin' : ''} /> Refresh
                        </Button>
                        <Button
                            onClick={() => setModalConfig({ isOpen: true, notification: null })}
                            variant="primary"
                            size="sm"
                        >
                            <IoAddOutline size={20} /> Create New
                        </Button>
                    </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={20} />
                            </span>
                            <input
                                type="text"
                                placeholder="Search by title or description..."
                                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-bold text-[#111827]"
                                onChange={(e) => debouncedSearch(e.target.value)}
                            />
                        </div>

                        <div className="flex flex-wrap items-center gap-3">
                            <select
                                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"
                                value={filters.filterType}
                                onChange={(e) => handleFilterChange('filterType', e.target.value)}
                            >
                                <option value="all">Status: Active</option>
                                <option value="deleted">Status: Deleted</option>
                            </select>

                            <select
                                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"
                                value={pagination.limit}
                                onChange={(e) => {
                                    setPagination({ ...pagination, limit: parseInt(e.target.value) })
                                    fetchNotifications(1, { ...filters })
                                }}
                            >
                                <option value="10">Show: 10</option>
                                <option value="25">Show: 25</option>
                                <option value="50">Show: 50</option>
                            </select>

                            <div className="flex items-center gap-2 bg-white px-4 py-2.5 rounded-xl border-2 border-gray-200">
                                <input
                                    type="date"
                                    className="bg-transparent border-none outline-none font-bold text-[#111827] text-sm"
                                    value={filters.startDate}
                                    onChange={(e) => handleFilterChange('startDate', e.target.value)}
                                />
                                <span className="text-gray-400 font-black">TO</span>
                                <input
                                    type="date"
                                    className="bg-transparent border-none outline-none font-bold text-[#111827] text-sm"
                                    value={filters.endDate}
                                    onChange={(e) => handleFilterChange('endDate', e.target.value)}
                                />
                            </div>

                            <Button
                                variant="outline"
                                onClick={clearFilters}
                                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-20 gap-4">
                            <IoRefreshOutline size={48} className="text-[#409CA4] animate-spin" />
                            <p className="text-lg font-black text-gray-400 uppercase tracking-widest">Loading Data...</p>
                        </div>
                    ) : (
                        <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">Notification Title</th>
                                    <th className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider">Created At</th>
                                    <th className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider text-center">Status</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">
                                {notifications.length === 0 ? (
                                    <tr>
                                        <td colSpan="5" className="px-6 py-24 text-center">
                                            <div className="flex flex-col items-center gap-4 text-gray-300">
                                                <IoNotificationsOutline size={64} className="opacity-20" />
                                                <p className="font-black text-xl uppercase tracking-wider">No notifications found</p>
                                            </div>
                                        </td>
                                    </tr>
                                ) : (
                                    notifications.map((notification, idx) => (
                                        <tr
                                            key={notification.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">#{notification.id}</td>
                                            <td className="px-6 py-5">
                                                <div
                                                    className="font-black text-lg text-[#111827] hover:text-[#409CA4] cursor-pointer transition-colors leading-tight"
                                                    onClick={() => setModalConfig({ isOpen: true, notification })}
                                                >
                                                    {notification.title}
                                                </div>
                                                <div className="text-sm font-bold text-gray-500 mt-1 line-clamp-1 opacity-70"
                                                    dangerouslySetInnerHTML={{ __html: notification.description?.substring(0, 120) + (notification.description?.length > 120 ? '...' : '') }}>
                                                </div>
                                            </td>
                                            <td className="px-6 py-5">
                                                <div className="text-sm font-black text-gray-700">
                                                    {new Date(notification.date_created).toLocaleString()}
                                                </div>
                                            </td>
                                            <td className="px-6 py-5 text-center">
                                                <Badge variant={notification.status === 1 ? 'success' : 'secondary'} size="sm">
                                                    {notification.status === 1 ? 'Active' : 'Inactive'}
                                                </Badge>
                                            </td>
                                            <td className="px-6 py-5">
                                                <div className="flex items-center justify-end gap-2">
                                                    <button
                                                        onClick={() => setModalConfig({ isOpen: true, notification })}
                                                        className="p-2.5 text-[#409CA4] hover:bg-[#409CA4]/10 rounded-xl transition-all shadow-sm bg-white border border-gray-100"
                                                    >
                                                        <IoPencilOutline size={20} />
                                                    </button>
                                                    {filters.filterType === 'deleted' ? (
                                                        <button
                                                            onClick={() => handleRestore(notification.id)}
                                                            className="p-2.5 text-[#5cb85c] hover:bg-[#5cb85c]/10 rounded-xl transition-all shadow-sm bg-white border border-gray-100"
                                                        >
                                                            <IoRefreshOutline size={20} />
                                                        </button>
                                                    ) : (
                                                        <button
                                                            onClick={() => handleDelete(notification.id)}
                                                            className="p-2.5 text-[#e8713a] hover:bg-red-50 rounded-xl transition-all shadow-sm bg-white border border-gray-100"
                                                        >
                                                            <IoTrashOutline size={20} />
                                                        </button>
                                                    )}
                                                </div>
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    )}
                </div>

                {/* ── Pagination Footer ── */}
                {notifications.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 }}>{(pagination.page - 1) * pagination.limit + 1}</strong>
                            {' '}to <strong style={{ color: TEAL }}>{Math.min(pagination.page * pagination.limit, pagination.total)}</strong>
                            {' '}of <strong style={{ color: TEAL }}>{pagination.total}</strong> notifications
                        </p>
                        <div className="flex items-center gap-1.5">
                            <button
                                onClick={() => handlePageChange(1)}
                                disabled={pagination.page === 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={() => handlePageChange(pagination.page - 1)}
                                disabled={pagination.page === 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={() => handlePageChange(p)}
                                    className={`px-4 py-2 rounded-xl text-xs font-black border-2 transition-all ${p === pagination.page
                                            ? 'bg-[#409CA4] text-white border-[#409CA4] shadow-lg scale-110'
                                            : 'bg-white border-gray-200 text-[#409CA4] hover:border-[#409CA4]'
                                        }`}
                                >
                                    {p}
                                </button>
                            ))}
                            <button
                                onClick={() => handlePageChange(pagination.page + 1)}
                                disabled={pagination.page === pagination.pages}
                                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={() => handlePageChange(pagination.pages)}
                                disabled={pagination.page === pagination.pages}
                                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>

            {/* Modal */}
            <NotificationModal
                isOpen={modalConfig.isOpen}
                onClose={() => setModalConfig({ isOpen: false, notification: null })}
                onSubmit={handleModalSubmit}
                notification={modalConfig.notification}
            />
        </div>
    )
}

export default Notifications
