import { useMemo, useState } from 'react'
import { UserPlus, Eye, X, Search, Pencil, Trash2, QrCode, ScanLine, Users as UsersIcon, AlertTriangle } from 'lucide-react'
import { useLiveRows } from '../../shared/hooks/useLiveRows'
import { PageLoading } from '../../shared/components/PageLoading'

/* ---------------------------------------------------------------------- */
/*  MOCK DATA                                                              */
/* ---------------------------------------------------------------------- */
const CATEGORIES = ['Senior Advocate', 'Junior Advocate', 'Law Intern', 'Clerk/Munshi', 'Office Assistant']
const FILTER_CATEGORIES = ['All', ...CATEGORIES]

const INITIAL_ADVOCATES = [
  { id: 'ADV-001', name: 'Manvendra Pratap Singh', category: 'Senior Advocate', enrollment: 'UP/1284/2009', membership: 'BAR-009921', practiceType: 'Civil & Revenue', chamberId: 'SIT-BAR-CH-001', joining: '2009-03-12', mobile: '+91 98765 43210', email: 'manvendra@barlaw.in', status: 'Active', nfcStatus: 'Issued' },
  { id: 'ADV-002', name: 'Rekha Awasthi', category: 'Senior Advocate', enrollment: 'UP/1577/2012', membership: 'BAR-009933', practiceType: 'Family Law', chamberId: 'SIT-BAR-CH-014', joining: '2012-07-21', mobile: '+91 98765 11220', email: 'rekha@barlaw.in', status: 'Active', nfcStatus: 'Issued' },
  { id: 'ADV-003', name: 'Devansh Kapoor', category: 'Junior Advocate', enrollment: 'UP/2390/2019', membership: 'BAR-010044', practiceType: 'Criminal', chamberId: 'SIT-BAR-CH-001', joining: '2019-01-15', mobile: '+91 99888 22110', email: 'devansh@barlaw.in', status: 'Active', nfcStatus: 'Issued' },
  { id: 'ADV-004', name: 'Saanvi Mehta', category: 'Junior Advocate', enrollment: 'UP/2410/2020', membership: 'BAR-010102', practiceType: 'Corporate', chamberId: 'SIT-BAR-CH-001', joining: '2020-06-09', mobile: '+91 97700 33445', email: 'saanvi@barlaw.in', status: 'Active', nfcStatus: 'Issued' },
  { id: 'ADV-005', name: 'Priya Bhargava', category: 'Senior Advocate', enrollment: 'UP/0980/2005', membership: 'BAR-008812', practiceType: 'Property Law', chamberId: 'SIT-BAR-CH-022', joining: '2005-11-02', mobile: '+91 94433 77665', email: 'priya@barlaw.in', status: 'Suspended', nfcStatus: 'Blocked' },
  { id: 'ADV-006', name: 'Karan Vohra', category: 'Junior Advocate', enrollment: 'UP/2655/2022', membership: 'BAR-010301', practiceType: 'Civil', chamberId: '', joining: '2022-09-18', mobile: '+91 93322 66554', email: 'karan@barlaw.in', status: 'Active', nfcStatus: 'Pending' },
  { id: 'ADV-007', name: 'Isha Choudhary', category: 'Junior Advocate', enrollment: 'UP/2701/2023', membership: 'BAR-010322', practiceType: 'Family Law', chamberId: '', joining: '2023-02-04', mobile: '+91 92211 55443', email: 'isha@barlaw.in', status: 'Active', nfcStatus: 'Pending' },
  { id: 'ADV-008', name: 'Arjun Tiwari', category: 'Law Intern', enrollment: '', membership: '', practiceType: 'General', chamberId: 'SIT-BAR-CH-001', joining: '2024-08-01', mobile: '+91 96655 99887', email: 'arjun@barlaw.in', status: 'Active', nfcStatus: 'Issued' },
  { id: 'ADV-009', name: 'Naveen Kumar', category: 'Clerk/Munshi', enrollment: '', membership: '', practiceType: 'Administrative', chamberId: 'SIT-BAR-CH-001', joining: '2018-04-22', mobile: '+91 95544 88776', email: 'naveen@barlaw.in', status: 'Active', nfcStatus: 'Issued' },
  { id: 'ADV-010', name: 'Suresh Pal', category: 'Office Assistant', enrollment: '', membership: '', practiceType: 'Administrative', chamberId: 'SIT-BAR-CH-014', joining: '2021-10-30', mobile: '+91 91100 44332', email: 'suresh@barlaw.in', status: 'Active', nfcStatus: 'Issued' },
]

const emptyForm = {
  name: '', category: 'Junior Advocate', enrollment: '', membership: '', practiceType: '',
  chamberId: '', joining: '', mobile: '', email: '', status: 'Active', nfcStatus: 'Pending'
}

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
const STATUS_STYLES = {
  Active: 'bg-emerald-50 text-emerald-600 border border-emerald-200',
  Suspended: 'bg-red-50 text-red-600 border border-red-200',
  Issued: 'bg-emerald-50 text-emerald-600 border border-emerald-200',
  Pending: 'bg-amber-50 text-amber-600 border border-amber-200',
  Blocked: 'bg-red-50 text-red-600 border border-red-200',
}

function StatusBadge({ status }) {
  const cls = STATUS_STYLES[status] || 'bg-gray-100 text-gray-500'
  return <span className={`text-[11px] font-medium px-2.5 py-1 rounded-full whitespace-nowrap ${cls}`}>{status}</span>
}

function Toggle({ checked, onChange }) {
  return (
    <button
      onClick={onChange}
      className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors shrink-0 ${checked ? 'bg-red-600' : 'bg-gray-300'}`}
    >
      <span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${checked ? 'translate-x-4' : 'translate-x-1'}`} />
    </button>
  )
}

function Toast({ message, type }) {
  if (!message) return null
  const tone = type === 'error' ? 'bg-red-600' : 'bg-gray-900'
  return <div className={`fixed bottom-6 right-6 ${tone} text-white text-sm px-4 py-2.5 rounded-md shadow-lg z-50 max-w-sm`}>{message}</div>
}

function fieldClass() {
  return 'w-full px-3 py-2 text-sm rounded-md border border-gray-200 bg-gray-50 focus:bg-white focus:outline-none focus:ring-2 focus:ring-red-200 focus:border-red-300'
}

function NFCCardVisual({ advocate, mode, onToggleMode }) {
  return (
    <div className="bg-gradient-to-br from-gray-900 to-red-900 rounded-lg p-5 text-white relative overflow-hidden w-full max-w-xs">
      <div className="flex items-center justify-between mb-6">
        <span className="text-[10px] tracking-widest text-white/70 uppercase">
          {mode === 'qr' ? 'Scan to Verify' : 'Tap to Verify'}
        </span>
        <button
          onClick={onToggleMode}
          className="flex items-center gap-1 text-[10px] font-medium px-2 py-1 rounded-md bg-white/10 hover:bg-white/20"
        >
          {mode === 'qr' ? <ScanLine size={11} /> : <QrCode size={11} />} {mode === 'qr' ? 'NFC' : 'QR'}
        </button>
      </div>
      {mode === 'qr' ? (
        <div className="flex justify-center mb-6">
          <div className="bg-white p-3 rounded-md">
            <div
              className="w-32 h-32"
              style={{
                backgroundImage:
                  'repeating-linear-gradient(0deg, #000 0 4px, transparent 4px 8px), repeating-linear-gradient(90deg, #000 0 4px, transparent 4px 8px)',
                backgroundBlendMode: 'multiply',
              }}
            />
          </div>
        </div>
      ) : (
        <div className="flex justify-center mb-6">
          <div className="w-20 h-20 rounded-full border-4 border-white/30 flex items-center justify-center">
            <ScanLine size={28} className="text-white/80" />
          </div>
        </div>
      )}
      <p className="text-center text-sm font-semibold">{advocate.name}</p>
      <p className="text-center text-[11px] text-white/60 mt-0.5">{advocate.chamberId || advocate.membership || advocate.id}</p>
    </div>
  )
}

function Modal({ open, onClose, title, footer, width = 'max-w-lg', children }) {
  if (!open) return null
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-gray-900/40 p-4" onClick={onClose}>
      <div className={`w-full ${width} rounded-lg bg-white shadow-xl max-h-[90vh] flex flex-col`} onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between border-b border-gray-200 p-4 shrink-0">
          <h3 className="text-sm font-semibold text-gray-900">{title}</h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600"><X size={16} /></button>
        </div>
        <div className="p-5 overflow-y-auto">{children}</div>
        {footer && <div className="flex justify-end gap-2 border-t border-gray-200 p-4 shrink-0">{footer}</div>}
      </div>
    </div>
  )
}

function ConfirmDialog({ open, onClose, onConfirm, title, description }) {
  if (!open) return null
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-gray-900/40 p-4" onClick={onClose}>
      <div className="w-full max-w-sm rounded-lg bg-white shadow-xl" onClick={e => e.stopPropagation()}>
        <div className="p-5">
          <div className="w-10 h-10 rounded-full bg-red-50 text-red-600 flex items-center justify-center mb-3">
            <AlertTriangle size={18} />
          </div>
          <h3 className="text-sm font-semibold text-gray-900">{title}</h3>
          <p className="text-sm text-gray-500 mt-1.5">{description}</p>
        </div>
        <div className="flex justify-end gap-2 border-t border-gray-200 p-4">
          <button onClick={onClose} className="px-4 py-2 text-sm rounded-md text-gray-600 hover:bg-gray-100">Cancel</button>
          <button onClick={onConfirm} className="px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium">Remove</button>
        </div>
      </div>
    </div>
  )
}

function RowActions({ onQr, onEdit, onDelete }) {
  return (
    <div className="flex items-center justify-end gap-1">
      <button onClick={onQr} title="View digital ID" className="w-7 h-7 rounded-md flex items-center justify-center text-gray-400 hover:bg-gray-100 hover:text-gray-700">
        <QrCode size={14} />
      </button>
      <button onClick={onEdit} title="Edit" className="w-7 h-7 rounded-md flex items-center justify-center text-gray-400 hover:bg-gray-100 hover:text-gray-700">
        <Pencil size={14} />
      </button>
      <button onClick={onDelete} title="Remove" className="w-7 h-7 rounded-md flex items-center justify-center text-gray-400 hover:bg-red-50 hover:text-red-600">
        <Trash2 size={14} />
      </button>
    </div>
  )
}

/* simple themed table + built-in search, replaces DataTable */
function DataTable({ columns, rows, searchKeys = [] }) {
  const [search, setSearch] = useState('')

  const filtered = useMemo(() => {
    if (!search) return rows
    const q = search.toLowerCase()
    return rows.filter(r => searchKeys.some(k => String(r[k] ?? '').toLowerCase().includes(q)))
  }, [rows, search, searchKeys])

  return (
    <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center gap-2 px-3 py-2 rounded-md w-full max-w-xs bg-gray-50 border border-gray-200">
          <Search size={14} className="text-gray-400" />
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Search records..."
            className="bg-transparent outline-none text-sm w-full placeholder:text-gray-400"
          />
        </div>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-gray-50 text-gray-500 text-xs uppercase tracking-wide">
              {columns.map(c => (
                <th key={c.key} className={`font-medium px-4 py-3 ${c.key === 'actions' ? 'text-right' : 'text-left'}`}>
                  {c.label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {filtered.map((r, i) => (
              <tr key={r.id || i} className="hover:bg-gray-50">
                {columns.map(c => (
                  <td key={c.key} className={`px-4 py-3 text-gray-700 ${c.key === 'actions' ? 'text-right' : ''}`}>
                    {c.render ? c.render(r) : r[c.key]}
                  </td>
                ))}
              </tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={columns.length} className="text-center text-gray-400 py-10 text-sm">No records match your search.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}

function Topbar({ title, subtitle, action }) {
  return (
    <div className="sticky top-0 z-10 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between gap-3 flex-wrap">
      <div className="flex items-center gap-2">
        <span className="w-8 h-8 rounded-md bg-red-600 text-white flex items-center justify-center shrink-0">
          <UsersIcon size={15} />
        </span>
        <div>
          <h1 className="text-lg font-semibold text-gray-900 leading-tight">{title}</h1>
          {subtitle && <p className="text-xs text-gray-500 max-w-2xl">{subtitle}</p>}
        </div>
      </div>
      {action}
    </div>
  )
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE                                                              */
/* ---------------------------------------------------------------------- */
export default function Members() {
  const { rows: advocates, loading, add, update, remove, toggleField } = useLiveRows('advocates')
  const [toast, setToast] = useState({ message: '', type: 'success' })

  const [category, setCategory] = useState('All')
  const [editing, setEditing] = useState(null) // null = closed, {} = new, {...row} = edit
  const [viewing, setViewing] = useState(null) // QR / ID card preview
  const [cardModes, setCardModes] = useState({})
  const [deleting, setDeleting] = useState(null)
  const [form, setForm] = useState(emptyForm)

  const showToast = (msg, type = 'success') => {
    setToast({ message: msg, type })
    setTimeout(() => setToast({ message: '', type: 'success' }), 2500)
  }

  const toggleActive = async (row) => {
    try {
      await toggleField(row.id, 'status', row.status === 'Active' ? 'Suspended' : 'Active')
      showToast(`${row.name} marked ${row.status === 'Active' ? 'Suspended' : 'Active'}`)
    } catch (err) {
      showToast(err?.message || 'Update failed', 'error')
    }
  }

  const filtered = useMemo(
    () => (category === 'All' ? advocates : advocates.filter(a => a.category === category)),
    [category, advocates]
  )

  const openNew = () => { setForm(emptyForm); setEditing({}) }
  const openEdit = row => { setForm({ ...emptyForm, ...row }); setEditing(row) }
  const closeForm = () => setEditing(null)

  const submit = async (e) => {
    e.preventDefault()
    if (!form.name.trim()) return
    try {
      if (editing && editing.id) {
        await update(editing.id, form)
        showToast(`${form.name} updated`)
      } else {
        await add({
          ...form,
          photo: form.name.split(' ').map(n => n[0]).slice(0, 2).join('').toUpperCase(),
          seniorityYear: form.joining ? Number(form.joining.slice(0, 4)) : new Date().getFullYear(),
        })
        showToast(`${form.name} added`)
      }
      closeForm()
    } catch (err) {
      showToast(err?.message || 'Save failed', 'error')
    }
  }

  const getMode = id => cardModes[id] || 'nfc'
  const toggleMode = id => setCardModes(prev => ({ ...prev, [id]: getMode(id) === 'nfc' ? 'qr' : 'nfc' }))

  const columns = [
    { key: 'id', label: 'ID' },
    { key: 'name', label: 'Name' },
    { key: 'category', label: 'Category' },
    { key: 'enrollment', label: 'Enrollment No.', render: r => <span className="font-mono text-xs">{r.enrollment || '—'}</span> },
    { key: 'membership', label: 'Membership No.', render: r => <span className="font-mono text-xs">{r.membership || '—'}</span> },
    { key: 'practiceType', label: 'Practice Type' },
    { key: 'joining', label: 'Joining Date' },
    { key: 'status', label: 'Status', render: r => <StatusBadge status={r.status} /> },
    {
      key: 'active', label: 'Active', sortable: false,
      render: r => <Toggle checked={r.status === 'Active'} onChange={() => { toggleActive(r); showToast(`${r.name} marked ${r.status === 'Active' ? 'Suspended' : 'Active'}`) }} />
    },
    {
      key: 'actions', label: '', sortable: false,
      render: r => (
        <RowActions
          onQr={() => setViewing(r)}
          onEdit={() => openEdit(r)}
          onDelete={() => setDeleting(r)}
        />
      )
    }
  ]

  if (loading) {
    return (
      <div className="w-full min-h-screen bg-gray-50">
        <PageLoading label="Loading members…" />
      </div>
    )
  }

  return (
    <div className="w-full min-h-screen bg-gray-50 text-gray-900" style={{ fontFamily: "'IBM Plex Sans', 'Inter', sans-serif" }}>
      <style>{`@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@500&display=swap');`}</style>

      <Topbar
        title="Advocate Master Database"
        subtitle="Enrollment numbers, membership status, seniority year, chamber details, and Bar Council verification in one register."
        action={
          <button onClick={openNew} className="flex items-center gap-2 px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium">
            <UserPlus size={15} /> Add Member
          </button>
        }
      />

      <div className="p-6 space-y-5">
        <div className="flex flex-wrap gap-2">
          {FILTER_CATEGORIES.map(c => (
            <button
              key={c}
              onClick={() => setCategory(c)}
              className={`rounded-full px-3.5 py-1.5 text-xs font-semibold transition-colors ${
                category === c ? 'bg-red-600 text-white' : 'bg-white text-gray-600 border border-gray-200 hover:bg-gray-100'
              }`}
            >
              {c}
            </button>
          ))}
        </div>

        <DataTable columns={columns} rows={filtered} searchKeys={['name', 'enrollment', 'membership', 'id']} />

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
          <div className="bg-white border border-gray-200 rounded-lg p-4">
            <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">Bar Council Verification</p>
            <p className="mt-2 text-sm text-gray-600">Cross-checks enrollment numbers against the State Bar Council registry before a membership is marked active.</p>
          </div>
          <div className="bg-white border border-gray-200 rounded-lg p-4">
            <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">Membership Verification</p>
            <p className="mt-2 text-sm text-gray-600">Validates dues, chamber affiliation, and NFC issuance status together for a single source of truth.</p>
          </div>
          <div className="bg-white border border-gray-200 rounded-lg p-4">
            <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">Active / Suspended Status</p>
            <p className="mt-2 text-sm text-gray-600">Use the toggle in any row to flip a member's status — suspended members are automatically blocked from NFC entry and voting verification.</p>
          </div>
        </div>
      </div>

      {/* Add / Edit modal */}
      <Modal
        open={!!editing}
        onClose={closeForm}
        title={editing && editing.id ? `Edit ${editing.name}` : 'Add Member'}
        footer={
          <>
            <button onClick={closeForm} className="px-4 py-2 text-sm rounded-md text-gray-600 hover:bg-gray-100">Cancel</button>
            <button onClick={submit} className="px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium">
              {editing && editing.id ? 'Save Changes' : 'Add Member'}
            </button>
          </>
        }
      >
        <form onSubmit={submit} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">Full Name</label>
            <input required value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} className={fieldClass()} placeholder="e.g. Anjali Rao" />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Category</label>
              <select value={form.category} onChange={e => setForm({ ...form, category: e.target.value })} className={fieldClass()}>
                {CATEGORIES.map(c => <option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Status</label>
              <select value={form.status} onChange={e => setForm({ ...form, status: e.target.value })} className={fieldClass()}>
                <option>Active</option>
                <option>Suspended</option>
              </select>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Enrollment No.</label>
              <input value={form.enrollment} onChange={e => setForm({ ...form, enrollment: e.target.value })} className={fieldClass()} placeholder="UP/0000/0000" />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Membership No.</label>
              <input value={form.membership} onChange={e => setForm({ ...form, membership: e.target.value })} className={fieldClass()} placeholder="BAR-000000" />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Practice Type</label>
              <input value={form.practiceType} onChange={e => setForm({ ...form, practiceType: e.target.value })} className={fieldClass()} placeholder="Civil, Criminal…" />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Chamber ID</label>
              <input value={form.chamberId} onChange={e => setForm({ ...form, chamberId: e.target.value })} className={fieldClass()} placeholder="SIT-BAR-CH-001" />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Mobile</label>
              <input value={form.mobile} onChange={e => setForm({ ...form, mobile: e.target.value })} className={fieldClass()} placeholder="+91 90000 00000" />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Joining Date</label>
              <input type="date" value={form.joining} onChange={e => setForm({ ...form, joining: e.target.value })} className={fieldClass()} />
            </div>
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">Email</label>
            <input type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} className={fieldClass()} placeholder="name@barlaw.in" />
          </div>
        </form>
      </Modal>

      {/* QR / NFC card preview */}
      <Modal open={!!viewing} onClose={() => setViewing(null)} title="Digital Identity Card" width="max-w-sm">
        {viewing && (
          <div className="flex flex-col items-center gap-3">
            <NFCCardVisual advocate={viewing} mode={getMode(viewing.id)} onToggleMode={() => toggleMode(viewing.id)} />
            <div className="flex items-center gap-1.5 text-xs text-gray-400">
              <Eye size={13} /> Tap the badge in the corner to switch between NFC and QR view
            </div>
          </div>
        )}
      </Modal>

      <ConfirmDialog
        open={!!deleting}
        onClose={() => setDeleting(null)}
        onConfirm={async () => {
          try {
            await remove(deleting.id)
            showToast(`${deleting.name} removed from the register`, 'error')
          } catch (err) {
            showToast(err?.message || 'Delete failed', 'error')
          }
          setDeleting(null)
        }}
        title="Remove member?"
        description={deleting ? `This will permanently remove ${deleting.name} (${deleting.id}) from the advocate register.` : ''}
      />

      <Toast message={toast.message} type={toast.type} />
    </div>
  )
}