import { useMemo, useState } from 'react'
import { useLiveRows } from '../../shared/hooks/useLiveRows'
import { PageLoading } from '../../shared/components/PageLoading'
import { Search, MapPin, Phone, Mail, Briefcase, ScanLine, QrCode, BookUser } from 'lucide-react'

/* ---------------------------------------------------------------------- */
/*  MOCK DATA                                                              */
/* ---------------------------------------------------------------------- */
const INITIAL_ADVOCATES = [
  { id: 'ADV-001', name: 'Manvendra Pratap Singh', category: 'Senior Advocate', photo: 'MS', enrollment: 'UP/1284/2009', membership: 'BAR-009921', practiceType: 'Civil & Revenue', chamberId: 'SIT-BAR-CH-001', mobile: '+91 98765 43210', email: 'manvendra@barlaw.in' },
  { id: 'ADV-002', name: 'Rekha Awasthi', category: 'Senior Advocate', photo: 'RA', enrollment: 'UP/1577/2012', membership: 'BAR-009933', practiceType: 'Family Law', chamberId: 'SIT-BAR-CH-014', mobile: '+91 98765 11220', email: 'rekha@barlaw.in' },
  { id: 'ADV-003', name: 'Devansh Kapoor', category: 'Junior Advocate', photo: 'DK', enrollment: 'UP/2390/2019', membership: 'BAR-010044', practiceType: 'Criminal', chamberId: 'SIT-BAR-CH-001', mobile: '+91 99888 22110', email: 'devansh@barlaw.in' },
  { id: 'ADV-004', name: 'Saanvi Mehta', category: 'Junior Advocate', photo: 'SM', enrollment: 'UP/2410/2020', membership: 'BAR-010102', practiceType: 'Corporate', chamberId: 'SIT-BAR-CH-001', mobile: '+91 97700 33445', email: 'saanvi@barlaw.in' },
  { id: 'ADV-005', name: 'Priya Bhargava', category: 'Senior Advocate', photo: 'PB', enrollment: 'UP/0980/2005', membership: 'BAR-008812', practiceType: 'Property Law', chamberId: 'SIT-BAR-CH-022', mobile: '+91 94433 77665', email: 'priya@barlaw.in' },
  { id: 'ADV-006', name: 'Karan Vohra', category: 'Junior Advocate', photo: 'KV', enrollment: 'UP/2655/2022', membership: 'BAR-010301', practiceType: 'Civil', chamberId: '', mobile: '+91 93322 66554', email: 'karan@barlaw.in' },
  { id: 'ADV-007', name: 'Isha Choudhary', category: 'Junior Advocate', photo: 'IC', enrollment: 'UP/2701/2023', membership: 'BAR-010322', practiceType: 'Family Law', chamberId: '', mobile: '+91 92211 55443', email: 'isha@barlaw.in' },
  { id: 'ADV-008', name: 'Arjun Tiwari', category: 'Law Intern', photo: 'AT', enrollment: '', membership: '', practiceType: 'General', chamberId: 'SIT-BAR-CH-001', mobile: '+91 96655 99887', email: 'arjun@barlaw.in' },
]

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
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">
      <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-28 h-28"
              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-16 h-16 rounded-full border-4 border-white/30 flex items-center justify-center">
            <ScanLine size={24} 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 Topbar({ title, subtitle }) {
  return (
    <div className="sticky top-0 z-10 bg-white border-b border-gray-200 px-6 py-4">
      <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">
          <BookUser 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>
    </div>
  )
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE                                                              */
/* ---------------------------------------------------------------------- */
export default function Directory() {
  const { rows: advocates, loading } = useLiveRows('advocates')
  const [query, setQuery] = useState('')
  const [practiceArea, setPracticeArea] = useState('All')

  // Independent NFC/QR toggle state per advocate card.
  const [cardModes, setCardModes] = useState({})
  const getMode = id => cardModes[id] || 'profile'
  const toggleMode = id =>
    setCardModes(prev => ({
      ...prev,
      [id]: getMode(id) === 'profile' ? 'nfc' : getMode(id) === 'nfc' ? 'qr' : 'profile'
    }))

  const practiceAreas = ['All', ...new Set(advocates.map(a => a.practiceType).filter(p => p !== '—' && p))]

  const filtered = useMemo(() => {
    return advocates.filter(a => {
      const matchesQuery = a.name.toLowerCase().includes(query.toLowerCase()) || a.enrollment.includes(query)
      const matchesArea = practiceArea === 'All' || a.practiceType === practiceArea
      return matchesQuery && matchesArea
    })
  }, [query, practiceArea, advocates])

  if (loading) {
    return (
      <div className="w-full min-h-screen bg-gray-50">
        <PageLoading label="Loading directory…" />
      </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 Directory"
        subtitle="Searchable register of practicing advocates by name, enrollment number, practice area, experience, and court. Tap an icon to flip a card to its NFC or QR identity view."
      />

      <div className="p-6 space-y-5">
        <div className="bg-white border border-gray-200 rounded-lg p-4 flex flex-col gap-3 sm:flex-row sm:items-center">
          <div className="relative flex-1">
            <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
            <input
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Search by name or enrollment number…"
              className={`${fieldClass()} pl-9`}
            />
          </div>
          <select value={practiceArea} onChange={e => setPracticeArea(e.target.value)} className={`${fieldClass()} sm:w-56`}>
            {practiceAreas.map(p => <option key={p}>{p}</option>)}
          </select>
        </div>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {filtered.map(a => {
            const mode = getMode(a.id)
            return (
              <div key={a.id} className="bg-white border border-gray-200 rounded-lg p-5">
                {mode === 'profile' ? (
                  <>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="flex h-11 w-11 items-center justify-center rounded-full bg-red-50 text-sm font-bold text-red-600">
                          {a.photo}
                        </div>
                        <div>
                          <p className="text-sm font-semibold text-gray-900">{a.name}</p>
                          <p className="text-xs text-gray-400">{a.category}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-1 rounded-full bg-gray-100 p-0.5">
                        <button
                          onClick={() => setCardModes(prev => ({ ...prev, [a.id]: 'nfc' }))}
                          title="View NFC card"
                          className="rounded-full p-1.5 text-gray-400 hover:bg-white hover:text-red-600"
                        >
                          <ScanLine size={13} />
                        </button>
                        <button
                          onClick={() => setCardModes(prev => ({ ...prev, [a.id]: 'qr' }))}
                          title="View QR code"
                          className="rounded-full p-1.5 text-gray-400 hover:bg-white hover:text-red-600"
                        >
                          <QrCode size={13} />
                        </button>
                      </div>
                    </div>
                    <div className="mt-4 space-y-2 text-xs text-gray-500">
                      <p className="flex items-center gap-2"><Briefcase size={13} /> {a.practiceType}</p>
                      <p className="flex items-center gap-2"><Phone size={13} /> {a.mobile}</p>
                      <p className="flex items-center gap-2 truncate"><Mail size={13} /> {a.email}</p>
                      <p className="flex items-center gap-2"><MapPin size={13} /> Chamber {a.chamberId || 'Unassigned'}</p>
                    </div>
                  </>
                ) : (
                  <div>
                    <NFCCardVisual advocate={a} mode={mode} onToggleMode={() => toggleMode(a.id)} />
                    <button
                      onClick={() => setCardModes(prev => ({ ...prev, [a.id]: 'profile' }))}
                      className="mt-3 w-full flex items-center justify-center text-xs font-medium px-3 py-2 rounded-md border border-gray-200 text-gray-600 hover:bg-gray-100"
                    >
                      Back to Profile
                    </button>
                  </div>
                )}
              </div>
            )
          })}
          {filtered.length === 0 && (
            <p className="col-span-full py-10 text-center text-sm text-gray-400">No advocates match that search.</p>
          )}
        </div>
      </div>
    </div>
  )
}