import { useState, useMemo, useEffect } from 'react'
import {
  Plus, ScanLine, QrCode, CheckCircle2, Clock, Ban, X, RotateCcw,
  FileClock, Search, LayoutDashboard, CreditCard,
} from 'lucide-react'
import { useLiveRows } from '../../shared/hooks/useLiveRows'
import { PageLoading } from '../../shared/components/PageLoading'

/* ---------------------------------------------------------------------- */
/*  MOCK DATA                                                              */
/* ---------------------------------------------------------------------- */
const INITIAL_ADVOCATES = [
  { id: 1, name: 'Manvendra Pratap Singh', category: 'Senior Advocate', chamberId: 'SIT-BAR-CH-001', enrollment: 'UP/1284/2009', nfcStatus: 'Issued', membership: 'BAR-009921', mobile: '+91 98765 43210', practiceType: 'Civil & Revenue' },
  { id: 2, name: 'Rekha Awasthi', category: 'Senior Advocate', chamberId: 'SIT-BAR-CH-014', enrollment: 'UP/1577/2012', nfcStatus: 'Issued', membership: 'BAR-009933', mobile: '+91 98765 11220', practiceType: 'Family Law' },
  { id: 3, name: 'Devansh Kapoor', category: 'Junior Advocate', chamberId: 'SIT-BAR-CH-001', enrollment: 'UP/2390/2019', nfcStatus: 'Issued', membership: 'BAR-010044', mobile: '+91 99888 22110', practiceType: 'Criminal' },
  { id: 4, name: 'Saanvi Mehta', category: 'Junior Advocate', chamberId: 'SIT-BAR-CH-001', enrollment: 'UP/2410/2020', nfcStatus: 'Issued', membership: 'BAR-010102', mobile: '+91 97700 33445', practiceType: 'Corporate' },
  { id: 5, name: 'Arjun Tiwari', category: 'Law Intern', chamberId: 'SIT-BAR-CH-001', enrollment: '—', nfcStatus: 'Issued', membership: 'BAR-010210', mobile: '+91 96655 99887', practiceType: 'General' },
  { id: 6, name: 'Naveen Kumar', category: 'Clerk/Munshi', chamberId: 'SIT-BAR-CH-001', enrollment: '—', nfcStatus: 'Issued', membership: 'BAR-010255', mobile: '+91 95544 88776', practiceType: 'Administrative' },
  { id: 7, name: 'Priya Bhargava', category: 'Senior Advocate', chamberId: 'SIT-BAR-CH-022', enrollment: 'UP/0980/2005', nfcStatus: 'Blocked', membership: 'BAR-008812', mobile: '+91 94433 77665', practiceType: 'Property Law' },
  { id: 8, name: 'Karan Vohra', category: 'Junior Advocate', chamberId: '—', enrollment: 'UP/2655/2022', nfcStatus: 'Pending', membership: 'BAR-010301', mobile: '+91 93322 66554', practiceType: 'Civil' },
  { id: 9, name: 'Isha Choudhary', category: 'Junior Advocate', chamberId: '—', enrollment: 'UP/2701/2023', nfcStatus: 'Pending', membership: 'BAR-010322', mobile: '+91 92211 55443', practiceType: 'Family Law' },
  { id: 10, name: 'Suresh Pal', category: 'Office Assistant', chamberId: 'SIT-BAR-CH-014', enrollment: '—', nfcStatus: 'Issued', membership: 'BAR-010410', mobile: '+91 91100 44332', practiceType: 'Administrative' },
]

const STATUS_ICON = { Issued: CheckCircle2, Pending: Clock, Blocked: Ban }
const STATUS_STYLES = {
  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',
}

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
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'}`}
      title={checked ? 'Card active' : 'Card blocked'}
    >
      <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 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">
      <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.chamberId : advocate.membership}</p>
    </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'
}

/* ---------------------------------------------------------------------- */
/*  TOPBAR                                                                 */
/* ---------------------------------------------------------------------- */
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">
          <CreditCard 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 NFCCards() {
  const { rows: advocates, loading, update } = useLiveRows('advocates')
  const [selected, setSelected] = useState(null)
  useEffect(() => {
    if (advocates.length && !selected) setSelected(advocates[0])
  }, [advocates, selected])
  const [showIssueModal, setShowIssueModal] = useState(false)
  const [issueTarget, setIssueTarget] = useState('')
  const [search, setSearch] = useState('')
  const [toast, setToast] = useState({ message: '', type: 'success' })

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

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

  const blockToggle = async (row) => {
    const next = row.nfcStatus === 'Blocked' ? 'Issued' : 'Blocked'
    try {
      await update(row.id, { ...row, nfcStatus: next })
      showToast(`${row.name}'s NFC card ${next === 'Blocked' ? 'blocked' : 'reactivated'}`, next === 'Blocked' ? 'error' : 'success')
    } catch (err) {
      showToast(err?.message || 'Update failed', 'error')
    }
  }

  const rescan = async (row) => {
    try {
      await update(row.id, { ...row, nfcStatus: 'Issued' })
      showToast(`Chip re-scanned and re-verified for ${row.name}`)
    } catch (err) {
      showToast(err?.message || 'Update failed', 'error')
    }
  }

  const issueCard = async () => {
    const advocate = advocates.find(a => a.name === issueTarget) || advocates[0]
    if (advocate) {
      try {
        await update(advocate.id, { ...advocate, nfcStatus: 'Pending' })
        showToast(`Card queued for issuance — ${advocate.name} is now Pending Bar Council verification`)
      } catch (err) {
        showToast(err?.message || 'Update failed', 'error')
      }
    }
    setShowIssueModal(false)
  }

  const counts = advocates.reduce(
    (acc, a) => {
      acc[a.nfcStatus] = (acc[a.nfcStatus] || 0) + 1
      return acc
    },
    { Issued: 0, Pending: 0, Blocked: 0 }
  )

  const activeSelected = advocates.find(a => a.id === selected?.id) || selected

  const filteredAdvocates = useMemo(() => {
    const q = search.toLowerCase()
    if (!q) return advocates
    return advocates.filter(a =>
      `${a.name} ${a.enrollment} ${a.chamberId}`.toLowerCase().includes(q)
    )
  }, [advocates, search])

  if (loading) {
    return (
      <div className="w-full min-h-screen bg-gray-50">
        <PageLoading label="Loading NFC cards…" />
      </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="NFC Smart Bar Cards"
        subtitle="Issue, verify, and monitor NFC-based identity cards used for bar entry, library access, voting verification, and event registration. Every card can also fall back to a scannable QR code."
        action={
          <button
            onClick={() => { setIssueTarget(advocates[0]?.name || ''); setShowIssueModal(true) }}
            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"
          >
            <Plus size={15} /> Issue New Card
          </button>
        }
      />

      <div className="p-6 space-y-5">
        {/* STATS */}
        <section className="grid grid-cols-1 gap-4 sm:grid-cols-3">
          {Object.entries(counts).map(([status, count]) => {
            const Icon = STATUS_ICON[status]
            return (
              <div key={status} className="bg-white border border-gray-200 rounded-lg p-4 flex items-center gap-3">
                <div className="w-10 h-10 rounded-md bg-gray-100 flex items-center justify-center text-gray-500 shrink-0">
                  <Icon size={18} />
                </div>
                <div>
                  <p className="text-xs font-semibold uppercase tracking-wide text-gray-500">{status}</p>
                  <p className="text-xl font-semibold text-gray-900">{count}</p>
                </div>
              </div>
            )
          })}
        </section>

        <section className="grid grid-cols-1 gap-6 lg:grid-cols-[340px_1fr]">
          {/* CARD PREVIEW */}
          <div>
            <p className="mb-3 text-xs font-semibold uppercase tracking-wide text-gray-500">Card Preview</p>
            {activeSelected ? (
              <>
                <NFCCardVisual
                  advocate={activeSelected}
                  mode={getMode(activeSelected.id)}
                  onToggleMode={() => toggleMode(activeSelected.id)}
                />
                <div className="bg-white border border-gray-200 rounded-lg mt-4 p-4">
                  <div className="flex items-center justify-between">
                    <p className="text-sm font-semibold text-gray-900">{activeSelected.name}</p>
                    <Toggle checked={activeSelected.nfcStatus !== 'Blocked'} onChange={() => blockToggle(activeSelected)} />
                  </div>
                  <div className="mt-3 space-y-2 text-sm">
                    <div className="flex justify-between"><span className="text-gray-400">Membership No.</span><span className="font-mono text-gray-900 text-xs">{activeSelected.membership}</span></div>
                    <div className="flex justify-between"><span className="text-gray-400">Mobile</span><span className="text-gray-900">{activeSelected.mobile}</span></div>
                    <div className="flex justify-between"><span className="text-gray-400">Practice Area</span><span className="text-gray-900">{activeSelected.practiceType}</span></div>
                    <div className="flex justify-between items-center"><span className="text-gray-400">Card Status</span><StatusBadge status={activeSelected.nfcStatus} /></div>
                  </div>
                  <div className="mt-4 flex gap-2">
                    <button onClick={() => rescan(activeSelected)} className="flex-1 flex items-center justify-center gap-1.5 text-xs font-medium px-3 py-2 rounded-md border border-gray-200 text-gray-700 hover:bg-gray-100">
                      <RotateCcw size={14} /> Re-scan Chip
                    </button>
                    <button onClick={() => showToast('Access log: Bar Entry · Library · Voting — last 30 days')} className="flex-1 flex items-center justify-center gap-1.5 text-xs font-medium px-3 py-2 rounded-md border border-gray-200 text-gray-700 hover:bg-gray-100">
                      <FileClock size={14} /> View Logs
                    </button>
                  </div>
                </div>
              </>
            ) : (
              <p className="bg-white border border-gray-200 rounded-lg p-6 text-center text-sm text-gray-400">No advocate selected.</p>
            )}
          </div>

          {/* TABLE */}
          <div>
            <p className="mb-3 text-xs font-semibold uppercase tracking-wide text-gray-500">All Cards</p>

            <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">
                      <th className="text-left font-medium px-4 py-3">Advocate</th>
                      <th className="text-left font-medium px-4 py-3">Category</th>
                      <th className="text-left font-medium px-4 py-3">Chamber ID</th>
                      <th className="text-left font-medium px-4 py-3">Enrollment</th>
                      <th className="text-left font-medium px-4 py-3">NFC Status</th>
                      <th className="text-left font-medium px-4 py-3">Card Active</th>
                      <th className="text-left font-medium px-4 py-3">Card View</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {filteredAdvocates.map(r => {
                      const mode = getMode(r.id)
                      return (
                        <tr key={r.id} className="hover:bg-gray-50">
                          <td className="px-4 py-3">
                            <button onClick={() => setSelected(r)} className="text-left font-medium text-gray-900 hover:text-red-600">
                              {r.name}
                            </button>
                          </td>
                          <td className="px-4 py-3 text-gray-700">{r.category}</td>
                          <td className="px-4 py-3 font-mono text-xs text-gray-600">{r.chamberId || '—'}</td>
                          <td className="px-4 py-3 font-mono text-xs text-gray-600">{r.enrollment}</td>
                          <td className="px-4 py-3"><StatusBadge status={r.nfcStatus} /></td>
                          <td className="px-4 py-3">
                            <Toggle checked={r.nfcStatus !== 'Blocked'} onChange={() => blockToggle(r)} />
                          </td>
                          <td className="px-4 py-3">
                            <div className="inline-flex items-center rounded-full bg-gray-100 p-0.5">
                              <button
                                onClick={() => setCardModes(prev => ({ ...prev, [r.id]: 'nfc' }))}
                                title="NFC view"
                                className={`flex items-center gap-1 rounded-full px-2 py-1 text-[11px] font-semibold transition-colors ${
                                  mode === 'nfc' ? 'bg-white text-red-600 shadow-sm' : 'text-gray-400 hover:text-gray-600'
                                }`}
                              >
                                <ScanLine size={12} /> NFC
                              </button>
                              <button
                                onClick={() => setCardModes(prev => ({ ...prev, [r.id]: 'qr' }))}
                                title="QR code view"
                                className={`flex items-center gap-1 rounded-full px-2 py-1 text-[11px] font-semibold transition-colors ${
                                  mode === 'qr' ? 'bg-white text-red-600 shadow-sm' : 'text-gray-400 hover:text-gray-600'
                                }`}
                              >
                                <QrCode size={12} /> QR
                              </button>
                            </div>
                          </td>
                        </tr>
                      )
                    })}
                    {filteredAdvocates.length === 0 && (
                      <tr><td colSpan={7} className="text-center text-gray-400 py-10 text-sm">No records match your search.</td></tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </section>
      </div>

      {/* ISSUE CARD MODAL */}
      {showIssueModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-gray-900/40 p-4" onClick={() => setShowIssueModal(false)}>
          <div className="w-full max-w-md rounded-lg bg-white shadow-xl" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between border-b border-gray-200 p-4">
              <h3 className="text-sm font-semibold text-gray-900">Issue NFC Card</h3>
              <button onClick={() => setShowIssueModal(false)} className="text-gray-400 hover:text-gray-600"><X size={16} /></button>
            </div>
            <div className="space-y-4 p-5">
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1">Advocate / Member</label>
                <select value={issueTarget} onChange={e => setIssueTarget(e.target.value)} className={fieldClass()}>
                  {advocates.map(a => <option key={a.id}>{a.name}</option>)}
                </select>
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1">Card Use Cases</label>
                <div className="flex flex-wrap gap-2">
                  {['Bar Entry', 'Library Access', 'Voting Verification', 'Event Registration'].map(use => (
                    <label key={use} className="flex items-center gap-1.5 rounded-md border border-gray-200 px-2.5 py-1.5 text-xs text-gray-600">
                      <input type="checkbox" defaultChecked className="accent-red-600" /> {use}
                    </label>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-xs font-medium text-gray-500 mb-1">Fallback Access Method</label>
                <div className="flex gap-2">
                  <label className="flex flex-1 items-center gap-2 rounded-md border border-gray-200 px-3 py-2 text-xs text-gray-600">
                    <input type="checkbox" defaultChecked className="accent-red-600" /> NFC Tap
                  </label>
                  <label className="flex flex-1 items-center gap-2 rounded-md border border-gray-200 px-3 py-2 text-xs text-gray-600">
                    <input type="checkbox" defaultChecked className="accent-red-600" /> QR Scan
                  </label>
                </div>
              </div>
              <p className="rounded-md bg-amber-50 p-3 text-xs text-amber-700">
                The card will be queued for Bar Council verification before activation. A QR code is generated automatically as a backup for venues without NFC readers.
              </p>
            </div>
            <div className="flex justify-end gap-2 border-t border-gray-200 p-4">
              <button onClick={() => setShowIssueModal(false)} className="px-4 py-2 text-sm rounded-md text-gray-600 hover:bg-gray-100">Cancel</button>
              <button onClick={issueCard} className="px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium">Queue for Issuance</button>
            </div>
          </div>
        </div>
      )}

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