// frontend/src/pages/settings/staff/StaffList.jsx

import { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import { useToast } from '@/components/ui/Toast'
import PageHeader from '@/components/ui/PageHeader'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import SearchBar from '@/components/ui/SearchBar'
import DataTable from '@/components/ui/DataTable'
import Pagination from '@/components/ui/Pagination'
import Select from '@/components/ui/Select'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import Icon from '@/components/ui/Icon'

// ─── Role meta ─────────────────────────────────────────────────────────────

const ROLE_VARIANT = {
  sysadmin: 'danger',
  admin:    'warning',
  editor:   'info',
  user:     'neutral',
}

const ROLE_OPTIONS = [
  { value: '',         label: 'All Roles' },
  { value: 'sysadmin', label: 'Sysadmin' },
  { value: 'admin',    label: 'Admin' },
  { value: 'editor',   label: 'Editor' },
  { value: 'user',     label: 'User' },
]

// ─── Columns ───────────────────────────────────────────────────────────────

function buildColumns(navigate, user, onDeleteClick) {
  return [
    {
      key:   'name',
      label: 'Name',
      sortable: true,
      alwaysOn: true,
      render: (row) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
          {/* Avatar circle */}
          <div style={{
            width: '32px',
            height: '32px',
            borderRadius: 'var(--radius-full)',
            background: 'var(--color-primary-subtle)',
            border: '1px solid rgba(192,193,255,0.15)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            flexShrink: 0,
            fontFamily: 'var(--font-family-display)',
            fontWeight: 'var(--font-weight-semibold)',
            fontSize: 'var(--font-size-sm)',
            color: 'var(--color-primary)',
            letterSpacing: '0.02em',
          }}>
            {row.name?.charAt(0)?.toUpperCase() || '?'}
          </div>
          <span style={{
            fontWeight: 'var(--font-weight-medium)',
            color: 'var(--color-text-primary)',
            fontSize: 'var(--font-size-base)',
          }}>
            {row.name}
            {row.id === user?.sub && (
              <span style={{
                marginLeft: 'var(--space-2)',
                fontSize: 'var(--font-size-xs)',
                color: 'var(--color-text-muted)',
                fontStyle: 'italic',
              }}>
                (you)
              </span>
            )}
          </span>
        </div>
      ),
    },
    {
      key:   'email',
      label: 'Email',
      sortable: true,
      render: (row) => (
        <span style={{ color: 'var(--color-text-secondary)', fontSize: 'var(--font-size-sm)' }}>
          {row.email}
        </span>
      ),
    },
    {
      key:   'role',
      label: 'Role',
      sortable: true,
      render: (row) => (
        <StatusBadge variant={ROLE_VARIANT[row.role] || 'neutral'}>
          {row.role?.charAt(0).toUpperCase() + row.role?.slice(1)}
        </StatusBadge>
      ),
    },
    {
      key:   'is_active',
      label: 'Status',
      sortable: false,
      render: (row) => (
        <StatusBadge variant={row.is_active ? 'success' : 'neutral'}>
          {row.is_active ? 'Active' : 'Inactive'}
        </StatusBadge>
      ),
    },
    {
      key:      '_actions',
      label:    '',
      sortable: false,
      alwaysOn: true,
      render: (row) => {
        const canEdit   = !(user?.role === 'admin' && row.role === 'sysadmin')
        const canDelete = canEdit && row.id !== user?.sub
        if (!canEdit && !canDelete) return null
        return (
          <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}
               onClick={(e) => e.stopPropagation()}>
            {canEdit && (
              <Button
                variant="table-actions"
                size="sm"
                onClick={() => navigate(`/settings/staff/${row.id}/edit`)}
              >
                Edit
              </Button>
            )}
            {canDelete && (
              <Button
                variant="table-actions"
                size="sm"
                onClick={() => onDeleteClick(row)}
              >
                Delete
              </Button>
            )}
          </div>
        )
      },
    },
  ]
}

// ─── Main ─────────────────────────────────────────────────────────────────

export default function StaffList() {
  const navigate   = useNavigate()
  const { user }   = useAuth()
  const toast      = useToast()

  const [staff,        setStaff]       = useState([])
  const [loading,      setLoading]     = useState(true)
  const [search,       setSearch]      = useState('')
  const [roleFilter,   setRoleFilter]  = useState('')
  const [deleteTarget, setDeleteTarget] = useState(null)
  const [deleting,     setDeleting]    = useState(false)
  const [sortKey,      setSortKey]     = useState('name')
  const [sortDir,      setSortDir]     = useState('asc')
  const [page,         setPage]        = useState(1)
  const PAGE_SIZE = 20

  const fetchStaff = useCallback(async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (search)     params.set('search', search)
      if (roleFilter) params.set('role', roleFilter)
      const qs   = params.toString()
      const data = await api.get(`/staff${qs ? `?${qs}` : ''}`)
      setStaff(data.staff || [])
      setPage(1)
    } catch (err) {
      toast.danger('Failed to load staff', err.message)
    } finally {
      setLoading(false)
    }
  }, [search, roleFilter])

  useEffect(() => { fetchStaff() }, [fetchStaff])

  const handleDelete = async () => {
    if (!deleteTarget) return
    setDeleting(true)
    try {
      await api.delete(`/staff/${deleteTarget.id}`)
      toast.success('Staff member deleted', `${deleteTarget.name} has been removed.`)
      setDeleteTarget(null)
      fetchStaff()
    } catch (err) {
      toast.danger('Delete failed', err.message)
    } finally {
      setDeleting(false)
    }
  }

  const handleSort = (key, dir) => { setSortKey(key); setSortDir(dir) }

  // Client-side sort (API doesn't support sort params)
  const sorted = [...staff].sort((a, b) => {
    const av = a[sortKey] ?? ''
    const bv = b[sortKey] ?? ''
    const cmp = String(av).localeCompare(String(bv), undefined, { sensitivity: 'base', numeric: true })
    return sortDir === 'asc' ? cmp : -cmp
  })

  // Paginate
  const paginated = sorted.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE)

  const columns = buildColumns(navigate, user, setDeleteTarget)

  return (
    <div className="page-wrapper">
      <PageHeader
        title="Staff"
        subtitle="Manage team members and their access permissions"
      >
        <Button variant="primary" onClick={() => navigate('/settings/staff/new')}>
          <Icon name="add" size={15} />
          Add Staff Member
        </Button>
      </PageHeader>

      {/* Toolbar */}
      <div style={{ display: 'flex', gap: 'var(--space-3)', alignItems: 'center', flexWrap: 'wrap' }}>
        <div style={{ flex: '1 1 260px', maxWidth: '400px' }}>
          <SearchBar
            value={search}
            onChange={setSearch}
            placeholder="Search by name or email…"
          />
        </div>
        <div style={{ width: '160px' }}>
          <Select
            value={roleFilter}
            onChange={(e) => setRoleFilter(e.target.value)}
          >
            {ROLE_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>{o.label}</option>
            ))}
          </Select>
        </div>
        {!loading && (
          <span style={{
            fontSize: 'var(--font-size-sm)',
            color: 'var(--color-text-muted)',
            marginLeft: 'auto',
          }}>
            {sorted.length} {sorted.length === 1 ? 'member' : 'members'}
          </span>
        )}
      </div>

      {/* Table */}
      <DataTable
        columns={columns}
        data={paginated}
        loading={loading}
        sortKey={sortKey}
        sortDir={sortDir}
        onSort={handleSort}
        onRowClick={(row) => navigate(`/settings/staff/${row.id}`)}
        emptyMessage="No staff members found"
        emptyDescription={search || roleFilter ? 'Try adjusting your search or filter.' : 'Add the first staff member to get started.'}
      />

      {sorted.length > PAGE_SIZE && (
        <Pagination
          page={page}
          total={sorted.length}
          onPageChange={setPage}
          pageSize={PAGE_SIZE}
        />
      )}

      <ConfirmDialog
        open={!!deleteTarget}
        variant="danger"
        title="Delete Staff Member"
        message={`Are you sure you want to delete "${deleteTarget?.name}" (${deleteTarget?.email})? This cannot be undone.`}
        confirmLabel="Delete"
        loading={deleting}
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  )
}
