import { useState, useEffect, useCallback } from 'react'
import { IoAdd, IoPencil, IoTrash, IoRefreshOutline, IoSearchOutline, IoCalendarOutline, IoFilterOutline, IoDownloadOutline } from 'react-icons/io5'
import Navbar from '../components/common/Navbar'
import Button from '../components/common/Button'
import Badge from '../components/common/Badge'
import ConfirmDialog from '../components/common/ConfirmDialog'
import AddUserModal from '../components/AddUserModal'
import EditUserModal from '../components/EditUserModal'
import ViewUserModal from '../components/ViewUserModal'
import { showToast } from '../utils/toast'
import { usersAPI } from '../api/endpoints'
import { debounce } from '../utils/helpers'
import { useAuth } from '../utils/hooks'
import { SUBSCRIPTION_TYPE_OPTIONS, getSubscriptionTypeLabel } from '../utils/subscriptionTypes'

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

const Users = () => {
  const { user } = useAuth()
  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(true)
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [totalUsers, setTotalUsers] = useState(0)
  const [search, setSearch] = useState('')
  const [startDate, setStartDate] = useState('')
  const [endDate, setEndDate] = useState('')
  const [isAddModalOpen, setIsAddModalOpen] = useState(false)
  const [isEditModalOpen, setIsEditModalOpen] = useState(false)
  const [selectedUser, setSelectedUser] = useState(null)
  const [isViewModalOpen, setIsViewModalOpen] = useState(false)
  const [confirmDelete, setConfirmDelete] = useState(false)
  const [userToDelete, setUserToDelete] = useState(null)
  const [isDeleting, setIsDeleting] = useState(false)
  const [selectedItems, setSelectedItems] = useState([])
  const [limit, setLimit] = useState(10)
  const [filterType, setFilterType] = useState('all')
  const [subscriptionTypeFilter, setSubscriptionTypeFilter] = useState('all')

  const fetchUsers = useCallback(async (page = 1, searchTerm = '') => {
    setLoading(true)
    try {
      const response = await usersAPI.getUsers(page, limit, searchTerm, startDate, endDate, filterType, subscriptionTypeFilter)
      setUsers(response.data.data || [])
      const pagination = response.data.pagination || {}
      setCurrentPage(pagination.page || 1)
      setTotalPages(pagination.pages || 1)
      setTotalUsers(pagination.total || 0)
    } catch (error) {
      showToast.error('Failed to load users')
      console.error(error)
    } finally {
      setLoading(false)
    }
  }, [limit, filterType, startDate, endDate, subscriptionTypeFilter])

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

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

  const handleDateFilter = () => {
    setCurrentPage(1)
    fetchUsers(1, search)
  }

  const handleClearFilters = () => {
    setSearch('')
    setStartDate('')
    setEndDate('')
    setFilterType('all')
    setSubscriptionTypeFilter('all')
    setCurrentPage(1)
    fetchUsers(1, '')
  }

  const handleExport = async (bulk = false) => {
    try {
      let response
      if (bulk) {
        if (selectedItems.length === 0) return showToast.error('No items selected')
        response = await usersAPI.exportUsers(null, null, null, null, selectedItems, subscriptionTypeFilter)
      } else {
        response = await usersAPI.exportUsers(search, startDate, endDate, null, null, subscriptionTypeFilter)
      }
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', 'users_export.csv')
      document.body.appendChild(link)
      link.click()
      link.remove()
    } catch (error) {
      showToast.error('Failed to export users')
    }
  }

  const handleRowClick = (u) => {
    setSelectedUser(u)
    setIsViewModalOpen(true)
  }

  const handleSelectAll = (checked) => {
    setSelectedItems(checked ? users.map(u => u.user_id) : [])
  }

  const handleSelectItem = (id, checked) => {
    setSelectedItems(prev => checked ? [...prev, id] : prev.filter(i => i !== id))
  }

  useEffect(() => {
    fetchUsers(1, '')
  }, [])

  useEffect(() => {
    setCurrentPage(1)
    fetchUsers(1, search)
  }, [limit, filterType, subscriptionTypeFilter])

  const handleAddUser = async (data) => {
    try {
      await usersAPI.createUser(data)
      showToast.success('User created successfully')
      setIsAddModalOpen(false)
      fetchUsers(currentPage, search)
    } catch (error) {
      showToast.error(error.response?.data?.message || 'Failed to create user')
    }
  }

  const handleEditUser = async (data) => {
    try {
      await usersAPI.updateUser(selectedUser.user_id, data)
      showToast.success('User updated successfully')
      setIsEditModalOpen(false)
      setSelectedUser(null)
      fetchUsers(currentPage, search)
    } catch (error) {
      showToast.error(error.response?.data?.message || 'Failed to update user')
    }
  }

  const handleDeleteUser = async () => {
    if (!userToDelete) return
    setIsDeleting(true)
    try {
      await usersAPI.softDeleteUser(userToDelete.user_id)
      showToast.success('User deleted successfully')
      setConfirmDelete(false)
      setUserToDelete(null)
      fetchUsers(currentPage, search)
    } catch (error) {
      showToast.error(error.response?.data?.message || 'Failed to delete user')
    } finally {
      setIsDeleting(false)
    }
  }

  const handleRestoreUser = async (u) => {
    try {
      await usersAPI.restoreUser(u.user_id)
      showToast.success('User restored successfully')
      fetchUsers(currentPage, search)
    } catch (error) {
      showToast.error(error.response?.data?.message || 'Failed to restore user')
    }
  }

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

  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="Users Management" subtitle={`Managing ${totalUsers} total users`} />

      {/* ── 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">
              <span style={{ color: TEAL }}>👥</span> Users Management
            </h2>
            <p className="text-sm font-bold text-gray-500 mt-1">
              {selectedItems.length > 0
                ? <span style={{ color: ORANGE }}>{selectedItems.length} row(s) selected</span>
                : <span>Total <strong style={{ color: TEAL }}>{totalUsers}</strong> users found</span>}
            </p>
          </div>

          <div className="flex gap-2 flex-wrap items-center">
            <Button
              onClick={() => handleExport(false)}
              variant="warning"
              size="sm"
              className="bg-[#f0ad4e]"
            >
              <IoDownloadOutline size={20} /> Export CSV
            </Button>
            {selectedItems.length > 0 && (
              <Button
                onClick={() => handleExport(true)}
                variant="danger"
                size="sm"
                className="bg-[#e8713a]"
              >
                Export Selected
              </Button>
            )}
            <Button
              onClick={() => { setSelectedUser(null); setIsAddModalOpen(true) }}
              variant="primary"
              size="sm"
            >
              <IoAdd size={20} /> Add New User
            </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 flex-wrap">

            {/* 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 name, email, phone…"
                value={search}
                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={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>

              <select
                value={filterType}
                onChange={e => { setFilterType(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">Active Users</option>
                <option value="subscribed">Subscribed Only</option>
                <option value="deleted">Deleted Users</option>
              </select>

              <select
                value={subscriptionTypeFilter}
                onChange={e => { setSubscriptionTypeFilter(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 min-w-[280px]"
              >
                <option value="all">All Subscription Types</option>
                {SUBSCRIPTION_TYPE_OPTIONS.map(option => (
                  <option key={option.value} value={option.value}>{option.label}</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"
                  value={startDate}
                  onChange={e => setStartDate(e.target.value)}
                  className="bg-transparent border-none outline-none font-bold text-[#111827] text-sm"
                />
                <span className="text-gray-400 font-black">—</span>
                <input
                  type="date"
                  value={endDate}
                  onChange={e => setEndDate(e.target.value)}
                  className="bg-transparent border-none outline-none font-bold text-[#111827] text-sm"
                />
              </div>

              <Button
                onClick={handleDateFilter}
                variant="secondary"
                size="sm"
                className="rounded-xl px-5"
              >
                <IoCalendarOutline size={20} /> Filter
              </Button>

              <Button
                onClick={handleClearFilters}
                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 Users...</p>
            </div>
          ) : users.length > 0 ? (
            <table className="w-full text-left border-collapse">
              <thead>
                <tr style={{ backgroundColor: TEAL }}>
                  <th className="px-6 py-4 w-12 text-center">
                    <input
                      type="checkbox"
                      checked={selectedItems.length === users.length && users.length > 0}
                      onChange={e => handleSelectAll(e.target.checked)}
                      className="rounded cursor-pointer w-5 h-5 accent-white"
                    />
                  </th>
                  {['User Identity', 'Phone & Contact', 'Registration', 'Status', 'License', 'Actions'].map(h => (
                    <th key={h} className="px-6 py-4 text-xs font-black text-white uppercase tracking-wider whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {users.map((row, idx) => (
                  <tr
                    key={row.user_id}
                    style={{ backgroundColor: idx % 2 === 0 ? '#fff' : '#f8fbfc' }}
                    className="hover:bg-[#409CA4]/5 transition-colors group"
                  >
                    <td className="px-6 py-5 text-center">
                      <input
                        type="checkbox"
                        checked={selectedItems.includes(row.user_id)}
                        onChange={e => handleSelectItem(row.user_id, e.target.checked)}
                        className="rounded cursor-pointer w-5 h-5 accent-[#409CA4]"
                      />
                    </td>

                    <td className="px-6 py-5">
                      <div
                        onClick={() => handleRowClick(row)}
                        className="cursor-pointer group/user"
                      >
                        <p className="font-black text-lg text-[#111827] group-hover/user:text-[#409CA4] transition-colors leading-tight">
                          {row.first_name} {row.last_name}
                        </p>
                        <p className="text-sm font-bold text-gray-500 mt-1">{row.email}</p>
                      </div>
                    </td>

                    <td className="px-6 py-5">
                      <p className="text-base font-black text-gray-700">{row.phone || '—'}</p>
                    </td>

                    <td className="px-6 py-5">
                      <p className="text-base font-black text-gray-700">
                        {row.date_created ? new Date(row.date_created).toLocaleString() : '—'}
                      </p>
                    </td>

                    <td className="px-6 py-5">
                      <Badge variant={row.status === '1' || row.status === 'active' ? 'success' : 'warning'} size="sm">
                        {row.status === '1' || row.status === 'active' ? 'Active' : 'Inactive'}
                      </Badge>
                    </td>

                    <td className="px-6 py-5">
                      <Badge variant={row.license_code_status === 1 ? 'success' : 'secondary'} size="sm">
                        {row.license_code_status === 1 ? 'ACTIVE / PAID' : 'INACTIVE / FREE'}
                      </Badge>
                      <p className="text-[13px] font-bold text-gray-600 mt-1">{getSubscriptionTypeLabel(row.subscription_type)}</p>
                      {row.license_date && (
                        <p className="text-[13px] font-bold text-gray-600 mt-1 uppercase">Start: {new Date(row.license_date).toLocaleString()}</p>
                      )}
                      <p className="text-[13px] font-bold text-gray-600 mt-1 uppercase">Reports: {row.report_count || 0}</p>
                    </td>

                    <td className="px-6 py-5">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => { setSelectedUser(row); setIsEditModalOpen(true) }}
                          className="p-2.5 text-[#409CA4] hover:bg-[#409CA4]/10 rounded-xl transition-all shadow-sm bg-white border border-gray-100"
                        >
                          <IoPencil size={20} />
                        </button>
                        {row.status === 'deleted' ? (
                          <button
                            onClick={() => handleRestoreUser(row)}
                            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>
                        ) : (
                          user?.role === 'superadmin' && (
                            <button
                              onClick={() => { setUserToDelete(row); setConfirmDelete(true) }}
                              className="p-2.5 text-[#e8713a] hover:bg-red-50 rounded-xl transition-all shadow-sm bg-white border border-gray-100"
                            >
                              <IoTrash size={20} />
                            </button>
                          )
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <div className="flex flex-col items-center justify-center py-24 gap-4 text-gray-300">
              <IoFilterOutline size={64} className="opacity-20" />
              <p className="font-black text-xl uppercase tracking-wider">No matching users found</p>
            </div>
          )}
        </div>

        {/* ── Pagination Footer ── */}
        {users.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, totalUsers)}</strong>
              {' '}of <strong style={{ color: TEAL }}>{totalUsers}</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>

      {/* Modals */}
      <AddUserModal isOpen={isAddModalOpen} onClose={() => setIsAddModalOpen(false)} onSubmit={handleAddUser} />
      <EditUserModal
        isOpen={isEditModalOpen}
        user={selectedUser}
        onClose={() => { setIsEditModalOpen(false); setSelectedUser(null) }}
        onSubmit={handleEditUser}
      />
      <ViewUserModal
        isOpen={isViewModalOpen}
        user={selectedUser}
        onClose={() => { setIsViewModalOpen(false); setSelectedUser(null) }}
      />
      <ConfirmDialog
        isOpen={confirmDelete}
        onClose={() => { setConfirmDelete(false); setUserToDelete(null) }}
        onConfirm={handleDeleteUser}
        title="Delete User"
        message={`Are you sure you want to delete ${userToDelete?.first_name}? This action cannot be undone.`}
        confirmText="Delete"
        cancelText="Cancel"
        isDangerous
        isLoading={isDeleting}
      />
    </div>
  )
}

export default Users
