// frontend/src/pages/bellcloud/users/UserList.jsx

import { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import usePreferences from '@/hooks/usePreferences'
import PageHeader from '@/components/ui/PageHeader'
import Button from '@/components/ui/Button'
import DataTable from '@/components/ui/DataTable'
import StatusBadge from '@/components/ui/StatusBadge'
import Pagination from '@/components/ui/Pagination'
import SearchBar from '@/components/ui/SearchBar'
import Select from '@/components/ui/Select'
import RowActions from '@/components/ui/RowActions'
import Icon from '@/components/ui/Icon'
import DeleteUserModal from '@/modals/bellcloud/users/DeleteUserModal'
import UserListCardView from '@/pages/bellcloud/users/UserListCardView'

// ─── Constants ────────────────────────────────────────────────────────────────

const PREFS_KEY = 'bellcloud_users'

// ─── Column definitions ───────────────────────────────────────────────────────

const ALL_COLUMNS = [
  { key: 'status',      label: '',             pickerLabel: 'Status',     defaultOn: true,  width: '80px' },
  { key: 'name',        label: 'Name',         defaultOn: true,  alwaysOn: true },
  { key: 'email',       label: 'Email',        defaultOn: true  },
  { key: 'phone',       label: 'Phone',        defaultOn: true  },
  { key: 'title',       label: 'Title',        defaultOn: true  },
  { key: 'lastActive',  label: 'Last Active',  defaultOn: true  },
]

// ─── Helpers ──────────────────────────────────────────────────────────────────

function statusVariant(status) {
  if (status === 'active')  return 'success'
  if (status === 'blocked') return 'danger'
  return 'neutral'
}

function Muted({ children }) {
  return <span style={{ color: 'var(--color-text-muted)' }}>{children}</span>
}

// ─── UserList ─────────────────────────────────────────────────────────────────

export default function UserList() {
  const navigate = useNavigate()
  const { hasPermission } = useAuth()
  const canEdit = hasPermission('app_users', 'edit')

  const { prefs, setPref, ready } = usePreferences(PREFS_KEY)

  // Data
  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // Filters
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('')

  // Pagination
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)

  // View mode: 'table' | 'card'
  const [viewMode, setViewMode] = useState('table')

  // Delete modal
  const [deleteTarget, setDeleteTarget] = useState(null)
  const [deleteError, setDeleteError] = useState('')

  // ── Load prefs once ready ──────────────────────────────────────────────────
  useEffect(() => {
    if (!ready) return
    if (prefs.status_filter !== undefined) setStatusFilter(prefs.status_filter)
    if (prefs.page_size     !== undefined) setPageSize(prefs.page_size)
    if (prefs.view_mode     !== undefined) setViewMode(prefs.view_mode)
  }, [ready]) // eslint-disable-line react-hooks/exhaustive-deps

  // ── Fetch ──────────────────────────────────────────────────────────────────
  const fetchUsers = useCallback(async () => {
    setLoading(true)
    setError('')
    try {
      const params = new URLSearchParams()
      if (search) params.set('search', search)
      if (statusFilter) params.set('status', statusFilter)
      const qs = params.toString()
      const data = await api.get(`/users${qs ? `?${qs}` : ''}`)
      setUsers(data.users ?? [])
    } catch (err) {
      setError(err.message || 'Failed to load users.')
    } finally {
      setLoading(false)
    }
  }, [search, statusFilter])

  // Silent refresh — re-fetches data without triggering the loading skeleton.
  // Used after in-place actions like status changes so cards update without flashing.
  const silentRefreshUsers = useCallback(async () => {
    try {
      const params = new URLSearchParams()
      if (search) params.set('search', search)
      if (statusFilter) params.set('status', statusFilter)
      const qs = params.toString()
      const data = await api.get(`/users${qs ? `?${qs}` : ''}`)
      setUsers(data.users ?? [])
    } catch {
      // swallow — a silent refresh failure isn't worth an error banner
    }
  }, [search, statusFilter])

  useEffect(() => { fetchUsers() }, [fetchUsers])
  useEffect(() => { setPage(1) }, [search, statusFilter])

  // ── Handlers with pref persistence ────────────────────────────────────────
  function handleStatusFilter(value) {
    setStatusFilter(value)
    setPref('status_filter', value)
  }

  function handleViewMode(mode) {
    setViewMode(mode)
    setPref('view_mode', mode)
  }

  function handlePageSize(size) {
    setPageSize(size)
    setPage(1)
    setPref('page_size', size)
  }

  // ── Delete ─────────────────────────────────────────────────────────────────
  const handleDelete = async () => {
    if (!deleteTarget) return
    setDeleteError('')
    try {
      await api.delete(`/users/${deleteTarget.id}`)
      setDeleteTarget(null)
      fetchUsers()
    } catch (err) {
      setDeleteError(err.message || 'Failed to delete user.')
    }
  }

  // ── Pagination ─────────────────────────────────────────────────────────────
  const total      = users.length
  const pagedUsers = users.slice((page - 1) * pageSize, page * pageSize)

  // ── Table columns ──────────────────────────────────────────────────────────
  const tableColumns = ALL_COLUMNS.map((c) => ({
    key: c.key,
    label: c.label,
    width: c.width,
    render: (user) => {
      switch (c.key) {
        case 'status':
          return (
            <StatusBadge variant={statusVariant(user.status)} dot={false} size="sm">
              {user.status ? user.status.charAt(0).toUpperCase() + user.status.slice(1) : 'Unknown'}
            </StatusBadge>
          )
        case 'name':
          return (
            <span style={{ fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>
              {user.display_name || 'Unnamed User'}
            </span>
          )
        case 'email':
          return user.email || <Muted>—</Muted>
        case 'phone':
          return user.phone_number || <Muted>—</Muted>
        case 'title':
          return user.userTitle || <Muted>—</Muted>
        case 'lastActive':
          return user.lastActive
            ? <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{user.lastActive}</span>
            : <Muted>—</Muted>
        default:
          return <Muted>—</Muted>
      }
    },
  }))

  // Actions column — appended, never draggable
  tableColumns.push({
    key: '__actions',
    label: '',
    width: '56px',
    align: 'right',
    render: (user) => (
      <div onClick={(e) => e.stopPropagation()} style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <RowActions
          actions={[
            {
              label: 'View Details',
              icon: <Icon name="eye" size={14} />,
              onClick: () => navigate(`/users/${user.id}`),
            },
            ...(canEdit ? [
              {
                label: 'Edit',
                icon: <Icon name="edit" size={14} />,
                color: 'var(--color-info)',
                onClick: () => navigate(`/users/${user.id}/edit`),
              },
              {
                label: 'Delete',
                icon: <Icon name="delete" size={14} />,
                color: 'var(--color-danger)',
                divider: true,
                onClick: () => { setDeleteError(''); setDeleteTarget(user) },
              },
            ] : []),
          ]}
        />
      </div>
    ),
  })

  // ─────────────────────────────────────────────────────────────────────────

  return (
    <div className="page-wrapper">

      {/* Page header */}
      <PageHeader
        title="App Users"
        subtitle={!loading ? `${total} ${total === 1 ? 'user' : 'users'}` : undefined}
      >
        {canEdit && (
          <Button variant="primary" onClick={() => navigate('/users/new')}>
            Add User
          </Button>
        )}
      </PageHeader>

      {/* Filter toolbar */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-3)', alignItems: 'center', minWidth: 0 }}>
        <div style={{ flex: '1 1 0', minWidth: '180px' }}>
          <SearchBar
            value={search}
            onChange={setSearch}
            placeholder="Search by name, email, phone, or UID…"
          />
        </div>

        <Select
          value={statusFilter}
          onChange={(e) => handleStatusFilter(e.target.value)}
          placeholder="All Status"
          style={{ width: '140px', flexShrink: 0 }}
        >
          <option value="">All Status</option>
          <option value="active">Active</option>
          <option value="blocked">Blocked</option>
        </Select>

        {/* View toggle — height matches input via .icon-btn-group__btn padding override */}
        <div className="icon-btn-group" role="group" aria-label="View mode">
          <Button
            variant={viewMode === 'table' ? 'secondary' : 'ghost'}
            size="md"
            className="icon-btn-group__btn"
            aria-pressed={viewMode === 'table'}
            aria-label="Table view"
            onClick={() => handleViewMode('table')}
            icon={
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="1.75"
                strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <rect x="3" y="3" width="18" height="18" rx="2" />
                <path d="M3 9h18M3 15h18M9 3v18" />
              </svg>
            }
          />
          <Button
            variant={viewMode === 'card' ? 'secondary' : 'ghost'}
            size="md"
            className="icon-btn-group__btn"
            aria-pressed={viewMode === 'card'}
            aria-label="Card view"
            onClick={() => handleViewMode('card')}
            icon={
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="1.75"
                strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <rect x="3" y="3" width="7" height="7" rx="1" />
                <rect x="14" y="3" width="7" height="7" rx="1" />
                <rect x="3" y="14" width="7" height="7" rx="1" />
                <rect x="14" y="14" width="7" height="7" rx="1" />
              </svg>
            }
          />
        </div>
      </div>

      {/* Error banner */}
      {error && (
        <div
          role="alert"
          style={{
            backgroundColor: 'var(--color-danger-bg)',
            border: '1px solid var(--color-danger-container)',
            borderRadius: 'var(--radius-md)',
            padding: 'var(--space-3) var(--space-4)',
            color: 'var(--color-danger)',
            fontSize: 'var(--font-size-sm)',
          }}
        >
          {error}
        </div>
      )}

      {/* Data table / Card view */}
      {viewMode === 'card' ? (
        <>
          <UserListCardView
            users={pagedUsers}
            loading={loading}
            canEdit={canEdit}
            onView={(user) => navigate(`/users/${user.id}`)}
            onEdit={(user) => navigate(`/users/${user.id}/edit`)}
            onDelete={(user) => { setDeleteError(''); setDeleteTarget(user) }}
            onRefresh={silentRefreshUsers}
            onMiddleClick={(user) => window.open(`/users/${user.id}`, '_blank', 'noopener,noreferrer')}
          />
          {total > 0 && (
            <Pagination
              page={page}
              pageSize={pageSize}
              total={total}
              onPageChange={setPage}
              onSizeChange={handlePageSize}
              pageSizes={[10, 20, 50]}
            />
          )}
        </>
      ) : (
        <DataTable
          columns={tableColumns}
          data={pagedUsers}
          loading={loading}
          keyField="id"
          emptyMessage="No users found"
          emptyDescription="Try adjusting your search or filters."
          onRowClick={(user) => navigate(`/users/${user.id}`)}
          onRowMiddleClick={(user) => window.open(`/users/${user.id}`, '_blank', 'noopener,noreferrer')}
          skeletonRows={8}
          footer={
            total > 0 && (
              <Pagination
                page={page}
                pageSize={pageSize}
                total={total}
                onPageChange={setPage}
                onSizeChange={handlePageSize}
                pageSizes={[10, 20, 50]}
              />
            )
          }
        />
      )}

      {/* Delete confirmation modal */}
      <DeleteUserModal
        user={deleteTarget}
        onConfirm={handleDelete}
        onCancel={() => { setDeleteTarget(null); setDeleteError('') }}
        error={deleteError}
      />

    </div>
  )
}
