import { useState, useMemo, useEffect } from 'react'
import { ShieldCheck, ArrowRightLeft, Clock3, GitBranch, Network, Search } from 'lucide-react'
import { useLiveRows } from '../../shared/hooks/useLiveRows'
import { PageLoading } from '../../shared/components/PageLoading'

/* ---------------------------------------------------------------------- */
/*  MOCK DATA                                                              */
/* ---------------------------------------------------------------------- */
const INITIAL_CHAMBERS = [
  { id: 1, chamberId: 'SIT-BAR-CH-001', senior: 'Manvendra Pratap Singh', establishedYear: 2009, verified: true, status: 'Active', juniors: 2, interns: 1, clerks: 1, assistants: 0 },
  { id: 2, chamberId: 'SIT-BAR-CH-014', senior: 'Rekha Awasthi', establishedYear: 2012, verified: true, status: 'Active', juniors: 3, interns: 2, clerks: 1, assistants: 1 },
  { id: 3, chamberId: 'SIT-BAR-CH-022', senior: 'Priya Bhargava', establishedYear: 2005, verified: false, status: 'Under Review', juniors: 2, interns: 2, clerks: 1, assistants: 0 },
  { id: 4, chamberId: 'SIT-BAR-CH-031', senior: 'Devraj Mishra', establishedYear: 2014, verified: true, status: 'Active', juniors: 1, interns: 1, clerks: 1, assistants: 0 },
]

const ADVOCATES = [
  { id: 1, name: 'Manvendra Pratap Singh', category: 'Senior Advocate', chamberId: 'SIT-BAR-CH-001', photo: 'MS', nfcStatus: 'Issued' },
  { id: 5, name: 'Devansh Kapoor', category: 'Junior Advocate', chamberId: 'SIT-BAR-CH-001', photo: 'DK', nfcStatus: 'Issued' },
  { id: 6, name: 'Saanvi Mehta', category: 'Junior Advocate', chamberId: 'SIT-BAR-CH-001', photo: 'SM', nfcStatus: 'Issued' },
  { id: 7, name: 'Arjun Tiwari', category: 'Law Intern', chamberId: 'SIT-BAR-CH-001', photo: 'AT', nfcStatus: 'Issued' },
  { id: 8, name: 'Naveen Kumar', category: 'Clerk/Munshi', chamberId: 'SIT-BAR-CH-001', photo: 'NK', nfcStatus: 'Issued' },
  { id: 2, name: 'Rekha Awasthi', category: 'Senior Advocate', chamberId: 'SIT-BAR-CH-014', photo: 'RA', nfcStatus: 'Issued' },
  { id: 9, name: 'Suresh Pal', category: 'Office Assistant', chamberId: 'SIT-BAR-CH-014', photo: 'SP', nfcStatus: 'Issued' },
  { id: 3, name: 'Priya Bhargava', category: 'Senior Advocate', chamberId: 'SIT-BAR-CH-022', photo: 'PB', nfcStatus: 'Blocked' },
  { id: 4, name: 'Devraj Mishra', category: 'Senior Advocate', chamberId: 'SIT-BAR-CH-031', photo: 'DM', nfcStatus: 'Issued' },
]

const INITIAL_TRANSFERS = [
  { id: 'TR-201', junior: 'Karan Vohra', from: 'Priya Bhargava', to: 'Rekha Awasthi', requestDate: '2026-06-12', status: 'Pending', newSeniorApproval: 'Pending' },
  { id: 'TR-202', junior: 'Isha Choudhary', from: 'Manvendra Pratap Singh', to: 'Rekha Awasthi', requestDate: '2026-06-20', status: 'Completed', newSeniorApproval: 'Approved' },
  { id: 'TR-203', junior: 'Arjun Tiwari', from: 'Devraj Mishra', to: 'Manvendra Pratap Singh', requestDate: '2026-06-25', status: 'Pending', newSeniorApproval: 'Pending' },
]

const CHAMBER_HISTORY = {
  'Karan Vohra': [
    { period: '2022 – 2024', senior: 'Priya Bhargava' },
    { period: '2024 – Present', senior: 'Rekha Awasthi' },
  ],
  'Isha Choudhary': [
    { period: '2023 – 2025', senior: 'Manvendra Pratap Singh' },
    { period: '2025 – Present', senior: 'Rekha Awasthi' },
  ],
}

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
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',
  Completed: 'bg-emerald-50 text-emerald-600 border border-emerald-200',
  Approved: 'bg-emerald-50 text-emerald-600 border border-emerald-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
      type="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>
}

/* themed table with built-in search, drop-in for 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="text-left font-medium px-4 py-3">{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.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() {
  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">
          <Network size={15} />
        </span>
        <div>
          <h1 className="text-lg font-semibold text-gray-900 leading-tight">Chamber Hierarchy Management</h1>
          <p className="text-xs text-gray-500 max-w-2xl">
            Every chamber is anchored to a Senior Advocate's NFC card and Chamber ID. Juniors, interns, clerks, and assistants link to that same ID.
          </p>
        </div>
      </div>
    </div>
  )
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE                                                              */
/* ---------------------------------------------------------------------- */
export default function ChamberHierarchy() {
  const { rows: chambers, loading: chambersLoading, update: updateChamber } = useLiveRows('chambers')
  const { rows: chamberTransfers, loading: transfersLoading, update: updateTransfer } = useLiveRows('chamberTransfers')
  const { rows: advocates, loading: advocatesLoading } = useLiveRows('advocates')
  const loading = chambersLoading || transfersLoading || advocatesLoading
  const [toast, setToast] = useState({ message: '', type: 'success' })

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

  const [activeChamberId, setActiveChamberId] = useState(null)
  useEffect(() => {
    if (chambers.length && !activeChamberId) {
      setActiveChamberId(chambers[0]?.chamberId)
    }
  }, [chambers, activeChamberId])
  const activeChamber = chambers.find(c => c.chamberId === activeChamberId) || chambers[0]

  const members = activeChamber ? advocates.filter(a => a.chamberId === activeChamber.chamberId) : []
  const senior = members.find(m => m.category === 'Senior Advocate')
  const team = members.filter(m => m.category !== 'Senior Advocate')

  const toggleVerified = async (c) => {
    const nextVerified = !c.verified
    try {
      await updateChamber(c.id, { ...c, verified: nextVerified, status: nextVerified ? 'Active' : 'Under Review' })
      showToast(`${c.chamberId} marked ${nextVerified ? 'Verified' : 'Under Review'}`, nextVerified ? 'success' : 'error')
    } catch (err) {
      showToast(err?.message || 'Update failed', 'error')
    }
  }

  const toggleTransferApproval = async (t) => {
    const next = t.status === 'Completed' ? 'Pending' : 'Completed'
    try {
      await updateTransfer(t.id, { ...t, status: next, newSeniorApproval: next === 'Completed' ? 'Approved' : 'Pending' })
      showToast(`Transfer ${t.id} marked ${next}`, next === 'Completed' ? 'success' : 'error')
    } catch (err) {
      showToast(err?.message || 'Update failed', 'error')
    }
  }

  const transferColumns = [
    { key: 'junior', label: 'Junior Advocate' },
    { key: 'from', label: 'From Senior' },
    { key: 'to', label: 'To Senior' },
    { key: 'requestDate', label: 'Requested' },
    { key: 'status', label: 'Status', render: r => <StatusBadge status={r.status} /> },
    {
      key: 'approved', label: 'Approved',
      render: r => <Toggle checked={r.status === 'Completed'} onChange={() => toggleTransferApproval(r)} />
    }
  ]

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

  if (!activeChamber) return null

  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 />

      <div className="p-6 space-y-6">
        <div className="flex flex-wrap gap-2">
          {chambers.map(c => (
            <button
              key={c.chamberId}
              type="button"
              onClick={() => setActiveChamberId(c.chamberId)}
              className={`rounded-lg border px-3.5 py-2 text-left text-xs transition-colors ${
                activeChamber.chamberId === c.chamberId
                  ? 'border-red-300 bg-red-50 text-red-700'
                  : 'border-gray-200 bg-white text-gray-600 hover:border-gray-300'
              }`}
            >
              <span className="block font-mono font-semibold">{c.chamberId}</span>
              <span className="block text-[11px] text-gray-400">{c.senior}</span>
            </button>
          ))}
        </div>

        <div className="grid grid-cols-1 gap-5 lg:grid-cols-[1fr_320px]">
          <div className="bg-white border border-gray-200 rounded-lg p-5">
            <div className="mb-4 flex items-center justify-between">
              <h2 className="flex items-center gap-2 text-base font-semibold text-gray-900">
                <GitBranch size={17} className="text-red-500" /> Chamber Tree — {activeChamber.chamberId}
              </h2>
              <div className="flex items-center gap-2">
                <span className={`inline-flex items-center gap-1 text-[11px] font-medium px-2.5 py-1 rounded-full ${
                  activeChamber.verified
                    ? 'bg-emerald-50 text-emerald-600 border border-emerald-200'
                    : 'bg-amber-50 text-amber-700 border border-amber-200'
                }`}>
                  <ShieldCheck size={13} /> {activeChamber.verified ? 'Verified Chamber' : 'Under Review'}
                </span>
                <Toggle checked={!!activeChamber.verified} onChange={() => toggleVerified(activeChamber)} />
              </div>
            </div>

            <div className="rounded-lg border border-gray-200 bg-gray-50 p-5">
              <div className="flex items-center gap-3">
                <div className="flex h-11 w-11 items-center justify-center rounded-full bg-red-600 text-sm font-bold text-white">
                  {senior?.photo || 'SA'}
                </div>
                <div>
                  <p className="text-sm font-semibold text-gray-900">{activeChamber.senior}</p>
                  <p className="text-xs text-gray-400">Senior Advocate · Est. {activeChamber.establishedYear}</p>
                </div>
              </div>

              <div className="ml-5 mt-4 space-y-2 border-l border-dashed border-gray-300 pl-6">
                {team.length === 0 && <p className="text-xs text-gray-400">No linked team members yet.</p>}
                {team.map(m => (
                  <div key={m.id} className="flex items-center gap-2.5 rounded-md bg-white px-3 py-2 border border-gray-200">
                    <div className="flex h-7 w-7 items-center justify-center rounded-full bg-red-50 text-[11px] font-bold text-red-600">
                      {m.photo}
                    </div>
                    <div className="flex-1">
                      <p className="text-sm font-medium text-gray-900">{m.name}</p>
                      <p className="text-[11px] text-gray-400">{m.category}</p>
                    </div>
                    <StatusBadge status={m.nfcStatus} />
                  </div>
                ))}
              </div>
            </div>

            <div className="mt-5 grid grid-cols-2 gap-3 sm:grid-cols-4">
              {[
                ['Juniors', activeChamber.juniors],
                ['Interns', activeChamber.interns],
                ['Clerks', activeChamber.clerks],
                ['Assistants', activeChamber.assistants]
              ].map(([label, val]) => (
                <div key={label} className="rounded-lg bg-gray-50 border border-gray-200 p-3 text-center">
                  <p className="text-xl font-semibold text-gray-900">{val}</p>
                  <p className="text-[11px] uppercase tracking-wide text-gray-400">{label}</p>
                </div>
              ))}
            </div>
          </div>

          <div className="space-y-4">
            <div className="bg-white border border-gray-200 rounded-lg p-4">
              <p className="mb-3 text-xs font-semibold uppercase tracking-wide text-gray-500">Chamber Verification Criteria</p>
              <ul className="space-y-2 text-sm text-gray-600">
                <li className="flex items-center gap-2"><ShieldCheck size={14} className="text-emerald-500" /> Active Membership</li>
                <li className="flex items-center gap-2"><ShieldCheck size={14} className="text-emerald-500" /> Active Team</li>
                <li className="flex items-center gap-2"><ShieldCheck size={14} className="text-emerald-500" /> Valid Enrollment</li>
              </ul>
            </div>

            <div className="bg-white border border-gray-200 rounded-lg p-4">
              <p className="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-gray-500">
                <Clock3 size={13} /> Experience Tracker
              </p>
              {Object.entries(CHAMBER_HISTORY).map(([name, history]) => (
                <div key={name} className="mb-3 last:mb-0">
                  <p className="text-sm font-medium text-gray-900">{name}</p>
                  <div className="mt-1 space-y-1">
                    {history.map((h, i) => (
                      <p key={i} className="text-xs text-gray-500">{h.period} — Under {h.senior}</p>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div>
          <h2 className="mb-3 flex items-center gap-2 text-base font-semibold text-gray-900">
            <ArrowRightLeft size={17} className="text-red-500" /> Chamber Transfer Requests
          </h2>
          <DataTable columns={transferColumns} rows={chamberTransfers} searchKeys={['junior', 'from', 'to']} />
        </div>
      </div>

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