import { useState, useMemo } from "react";
import {
  Gavel, Users, CalendarDays, ClipboardList,
  Pencil, Trash2, Plus, X, AlertTriangle,
  CheckCircle2, XCircle, Search,
} from "lucide-react";
import { useLiveRows } from "../../shared/hooks/useLiveRows";
import { PageLoading } from "../../shared/components/PageLoading";

/* ---------------------------------------------------------------------- */
/*  MOCK DATA                                                              */
/* ---------------------------------------------------------------------- */
const INITIAL_COMMITTEES = [
  { id: 'COM-001', name: 'Grievance Redressal Committee', chair: 'Manvendra Pratap Singh', members: 7, meetings: 12, openTasks: 3, resolutions: 24, active: true },
  { id: 'COM-002', name: 'Library & Publication Committee', chair: 'Rekha Awasthi', members: 5, meetings: 8, openTasks: 1, resolutions: 15, active: true },
  { id: 'COM-003', name: 'Welfare & Benevolent Fund', chair: 'Devraj Mishra', members: 6, meetings: 6, openTasks: 4, resolutions: 9, active: true },
  { id: 'COM-004', name: 'Enrolment & Verification', chair: 'Priya Bhargava', members: 4, meetings: 10, openTasks: 2, resolutions: 18, active: true },
  { id: 'COM-005', name: 'Sports & Cultural Committee', chair: 'Karan Vohra', members: 8, meetings: 4, openTasks: 0, resolutions: 6, active: false },
]

const emptyForm = { name: '', chair: '', members: 4, meetings: 0, openTasks: 0, resolutions: 0, active: true }

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
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 flex items-center gap-2 max-w-sm`}>
      {type === 'error' ? <XCircle size={15} /> : <CheckCircle2 size={15} />}
      {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 Modal({ open, onClose, title, children, footer }) {
  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-lg 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 px-5 py-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 px-5 py-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 px-5 py-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(); onClose(); }} className="px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium">
            Disband
          </button>
        </div>
      </div>
    </div>
  )
}

function Topbar({ onNew }) {
  return (
    <div className="sticky top-0 z-10 bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between flex-wrap gap-3">
      <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">
          <Gavel size={15} />
        </span>
        <div>
          <h1 className="text-lg font-semibold text-gray-900 leading-tight">Committee Management</h1>
          <p className="text-xs text-gray-500">Member assignment, meeting records, resolutions, and task tracking across standing committees.</p>
        </div>
      </div>
      <button
        onClick={onNew}
        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} /> New Committee
      </button>
    </div>
  )
}

/* ---------------------------------------------------------------------- */
/*  STAT CARD                                                              */
/* ---------------------------------------------------------------------- */
function StatCard({ icon: Icon, label, value, sub }) {
  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4">
      <div className="w-8 h-8 rounded-md bg-gray-100 text-gray-500 flex items-center justify-center mb-2">
        <Icon size={15} />
      </div>
      <div className="text-2xl font-semibold text-gray-900">{value}</div>
      <div className="text-xs text-gray-500 mt-1">{label}</div>
      {sub && <div className="text-[11px] text-gray-400 mt-0.5">{sub}</div>}
    </div>
  )
}

/* ---------------------------------------------------------------------- */
/*  COMMITTEE CARD                                                         */
/* ---------------------------------------------------------------------- */
function CommitteeCard({ c, onEdit, onDelete, onToggle }) {
  return (
    <div className={`bg-white border border-gray-200 rounded-lg p-5 flex flex-col gap-4 transition-opacity ${c.active === false ? 'opacity-60' : ''}`}>
      {/* Header */}
      <div className="flex items-start justify-between gap-2">
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold text-gray-900 leading-tight">{c.name}</p>
          <p className="mt-0.5 text-xs text-gray-400">Chaired by {c.chair}</p>
        </div>
        <span className="shrink-0 rounded-full bg-red-50 px-2.5 py-1 text-[11px] font-semibold text-red-600 font-mono">
          {c.id}
        </span>
      </div>

      {/* Stats grid */}
      <div className="grid grid-cols-3 gap-2 text-center">
        {[
          { icon: Users, label: 'Members', value: c.members },
          { icon: CalendarDays, label: 'Meetings', value: c.meetings },
          { icon: ClipboardList, label: 'Open Tasks', value: c.openTasks },
        ].map(({ icon: Icon, label, value }) => (
          <div key={label} className="rounded-lg bg-gray-50 border border-gray-100 p-2.5">
            <p className="flex items-center justify-center gap-1 text-[10px] uppercase tracking-wide text-gray-400 mb-1">
              <Icon size={10} /> {label}
            </p>
            <p className={`text-lg font-semibold ${label === 'Open Tasks' && value > 0 ? 'text-amber-600' : 'text-gray-900'}`}>
              {value}
            </p>
          </div>
        ))}
      </div>

      {/* Resolutions */}
      <div className="flex items-center justify-between border-t border-gray-100 pt-3 text-sm">
        <span className="text-gray-500 text-xs">Resolutions passed</span>
        <span className="font-semibold text-gray-900">{c.resolutions}</span>
      </div>

      {/* Footer */}
      <div className="flex items-center justify-between border-t border-gray-100 pt-3">
        <div className="flex items-center gap-2">
          <Toggle checked={c.active !== false} onChange={() => onToggle(c)} />
          <span className={`text-xs font-medium ${c.active !== false ? 'text-emerald-600' : 'text-gray-400'}`}>
            {c.active !== false ? 'Active' : 'Inactive'}
          </span>
        </div>
        <div className="flex items-center gap-1">
          <button
            onClick={() => onEdit(c)}
            className="w-7 h-7 rounded-md flex items-center justify-center text-gray-400 hover:bg-gray-100 hover:text-gray-700"
            title="Edit"
          >
            <Pencil size={14} />
          </button>
          <button
            onClick={() => onDelete(c)}
            className="w-7 h-7 rounded-md flex items-center justify-center text-gray-400 hover:bg-red-50 hover:text-red-600"
            title="Disband"
          >
            <Trash2 size={14} />
          </button>
        </div>
      </div>
    </div>
  )
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE                                                              */
/* ---------------------------------------------------------------------- */
export default function Committees() {
  const { rows: committees, loading, add, update, remove, toggleField } = useLiveRows('committees')
  const [toast, setToast] = useState({ message: '', type: 'success' })
  const [editing, setEditing] = useState(null)
  const [deleting, setDeleting] = useState(null)
  const [form, setForm] = useState(emptyForm)
  const [search, setSearch] = useState('')
  const [filterActive, setFilterActive] = useState('All') // 'All' | 'Active' | 'Inactive'

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

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

  const submit = async (e) => {
    e.preventDefault()
    if (!form.name.trim()) return
    const payload = { ...form, members: Number(form.members), meetings: Number(form.meetings), openTasks: Number(form.openTasks), resolutions: Number(form.resolutions) }
    try {
      if (editing && editing.id) {
        await update(editing.id, payload)
        showToast(`${form.name} updated`)
      } else {
        await add(payload)
        showToast(`${form.name} created`)
      }
      closeForm()
    } catch (err) {
      showToast(err?.message || 'Save failed', 'error')
    }
  }

  const toggleActive = async (c) => {
    const next = c.active === false
    try {
      await toggleField(c.id, 'active', next)
      showToast(`${c.name} marked ${next ? 'active' : 'inactive'}`)
    } catch (err) {
      showToast(err?.message || 'Update failed', 'error')
    }
  }

  const filtered = useMemo(() => {
    return committees.filter(c => {
      const matchesSearch = `${c.name} ${c.chair} ${c.id}`.toLowerCase().includes(search.toLowerCase())
      const matchesFilter = filterActive === 'All' || (filterActive === 'Active' ? c.active !== false : c.active === false)
      return matchesSearch && matchesFilter
    })
  }, [committees, search, filterActive])

  const stats = {
    total: committees.length,
    active: committees.filter(c => c.active !== false).length,
    totalMeetings: committees.reduce((s, c) => s + c.meetings, 0),
    openTasks: committees.reduce((s, c) => s + c.openTasks, 0),
  }

  if (loading) {
    return (
      <div className="w-full min-h-screen bg-gray-50">
        <PageLoading label="Loading committees…" />
      </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 onNew={openNew} />

      <div className="p-6 space-y-5">
        {/* STAT TILES */}
        <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
          <StatCard icon={Gavel} label="Total Committees" value={stats.total} />
          <StatCard icon={CheckCircle2} label="Active Committees" value={stats.active} sub={`${stats.total - stats.active} inactive`} />
          <StatCard icon={CalendarDays} label="Total Meetings Held" value={stats.totalMeetings} />
          <StatCard icon={ClipboardList} label="Open Tasks" value={stats.openTasks} sub={stats.openTasks > 0 ? 'Pending resolution' : 'All clear'} />
        </div>

        {/* TOOLBAR */}
        <div className="bg-white border border-gray-200 rounded-lg p-4 flex flex-wrap items-center gap-3">
          <div className="flex items-center gap-2 px-3 py-2 rounded-md w-64 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 by name, chair, ID..."
              className="bg-transparent outline-none text-sm w-full placeholder:text-gray-400"
            />
          </div>
          <div className="flex items-center gap-1 bg-gray-100 rounded-md p-1">
            {['All', 'Active', 'Inactive'].map(f => (
              <button
                key={f}
                onClick={() => setFilterActive(f)}
                className={`text-xs font-medium px-3 py-1.5 rounded-md transition-colors ${filterActive === f ? 'bg-white text-red-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
              >
                {f}
              </button>
            ))}
          </div>
          <span className="ml-auto text-xs text-gray-400">{filtered.length} of {committees.length} committees</span>
        </div>

        {/* COMMITTEE CARDS */}
        {filtered.length === 0 ? (
          <div className="bg-white border border-gray-200 rounded-lg py-14 text-center">
            <Gavel size={28} className="mx-auto text-gray-300 mb-3" />
            <p className="text-sm text-gray-400">No committees match your search.</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {filtered.map(c => (
              <CommitteeCard
                key={c.id}
                c={c}
                onEdit={openEdit}
                onDelete={setDeleting}
                onToggle={toggleActive}
              />
            ))}
          </div>
        )}
      </div>

      {/* ADD / EDIT MODAL */}
      <Modal
        open={!!editing}
        onClose={closeForm}
        title={editing && editing.id ? `Edit — ${editing.name}` : 'New Committee'}
        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' : 'Create Committee'}
            </button>
          </>
        }
      >
        <form onSubmit={submit} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">Committee Name</label>
            <input
              required
              value={form.name}
              onChange={e => setForm({ ...form, name: e.target.value })}
              className={fieldClass()}
              placeholder="e.g. Grievance Redressal Committee"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">Chairperson</label>
            <input
              value={form.chair}
              onChange={e => setForm({ ...form, chair: e.target.value })}
              className={fieldClass()}
              placeholder="Chairperson name"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Members</label>
              <input type="number" min="0" value={form.members} onChange={e => setForm({ ...form, members: e.target.value })} className={fieldClass()} />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Meetings Held</label>
              <input type="number" min="0" value={form.meetings} onChange={e => setForm({ ...form, meetings: e.target.value })} className={fieldClass()} />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Open Tasks</label>
              <input type="number" min="0" value={form.openTasks} onChange={e => setForm({ ...form, openTasks: e.target.value })} className={fieldClass()} />
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Resolutions Passed</label>
              <input type="number" min="0" value={form.resolutions} onChange={e => setForm({ ...form, resolutions: e.target.value })} className={fieldClass()} />
            </div>
          </div>
          <div className="flex items-center justify-between rounded-md border border-gray-200 bg-gray-50 px-4 py-3">
            <div>
              <p className="text-sm font-medium text-gray-700">Active Committee</p>
              <p className="text-xs text-gray-400">Inactive committees are hidden from governance views</p>
            </div>
            <Toggle checked={form.active !== false} onChange={() => setForm({ ...form, active: !(form.active !== false) })} />
          </div>
        </form>
      </Modal>

      {/* CONFIRM DISBAND */}
      <ConfirmDialog
        open={!!deleting}
        onClose={() => setDeleting(null)}
        onConfirm={async () => {
          try {
            await remove(deleting.id)
            showToast(`${deleting.name} disbanded`, 'error')
          } catch (err) {
            showToast(err?.message || 'Delete failed', 'error')
          }
          setDeleting(null)
        }}
        title="Disband committee?"
        description={deleting ? `This will permanently remove ${deleting.name} (${deleting.id}) from the association's records.` : ''}
      />

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