import { useState, useMemo } from "react";
import {
  Briefcase, Plus, Crown, Users2, Trash2,
  X, CheckCircle2, XCircle, Search, Filter,
} from "lucide-react";
import { useLiveRows } from "../../shared/hooks/useLiveRows";
import { PageLoading } from "../../shared/components/PageLoading";

/* ---------------------------------------------------------------------- */
/*  MOCK DATA                                                              */
/* ---------------------------------------------------------------------- */
const SENIOR_LEADERBOARD = [
  { senior: 'Manvendra Pratap Singh', total: 4 },
  { senior: 'Rekha Awasthi', total: 7 },
  { senior: 'Priya Bhargava', total: 5 },
  { senior: 'Devraj Mishra', total: 3 },
]

const INITIAL_LISTINGS = [
  { id: 'EMP-001', type: 'Senior Requirement', text: '1 Civil Law Junior Required — experienced in district court matters', postedBy: 'Manvendra Pratap Singh', practiceArea: 'Civil', posted: '2026-06-01', open: true },
  { id: 'EMP-002', type: 'Junior Requirement', text: 'Available for Criminal Law chambers — 2 years experience', postedBy: 'Karan Vohra', practiceArea: 'Criminal', posted: '2026-06-05', open: true },
  { id: 'EMP-003', type: 'Senior Requirement', text: 'Family Law intern needed for research and drafting', postedBy: 'Rekha Awasthi', practiceArea: 'Family Law', posted: '2026-06-10', open: true },
  { id: 'EMP-004', type: 'Senior Requirement', text: 'Revenue Law junior sought for land dispute cases', postedBy: 'Devraj Mishra', practiceArea: 'Revenue Law', posted: '2026-06-12', open: false },
  { id: 'EMP-005', type: 'Junior Requirement', text: 'Looking for Senior in Commercial Law — fresher from NLU', postedBy: 'Isha Choudhary', practiceArea: 'Commercial', posted: '2026-06-18', open: true },
]

const TYPES = ['Senior Requirement', 'Junior Requirement']
const PRACTICE_AREAS = ['Civil', 'Criminal', 'Revenue Law', 'Family Law', 'Commercial']
const emptyForm = { type: TYPES[0], text: '', postedBy: '', practiceArea: PRACTICE_AREAS[0] }

/* ---------------------------------------------------------------------- */
/*  SMALL UI                                                               */
/* ---------------------------------------------------------------------- */
function Toggle({ checked, onChange }) {
  return (
    <button
      type="button"
      onClick={() => onChange(!checked)}
      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-md rounded-lg bg-white shadow-xl flex flex-col max-h-[90vh]" 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 Topbar({ onPost }) {
  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">
          <Briefcase size={15} />
        </span>
        <div>
          <h1 className="text-lg font-semibold text-gray-900 leading-tight">Senior–Junior Matching</h1>
          <p className="text-xs text-gray-500">Seniors post requirements, juniors post availability, and the matching system connects them by practice area.</p>
        </div>
      </div>
      <button
        onClick={onPost}
        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} /> Post Requirement
      </button>
    </div>
  )
}

function StatCard({ icon: Icon, label, value, tone = 'gray' }) {
  const badge = tone === 'red' ? 'bg-red-600 text-white' : 'bg-gray-100 text-gray-500'
  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4">
      <div className={`w-8 h-8 rounded-md flex items-center justify-center mb-2 ${badge}`}>
        <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>
    </div>
  )
}

/* ---------------------------------------------------------------------- */
/*  TYPE PILL                                                              */
/* ---------------------------------------------------------------------- */
function TypePill({ type }) {
  const isSenior = type === 'Senior Requirement'
  return (
    <span className={`text-[11px] font-medium px-2.5 py-1 rounded-full whitespace-nowrap ${
      isSenior ? 'bg-red-50 text-red-600 border border-red-200' : 'bg-gray-100 text-gray-600 border border-gray-200'
    }`}>
      {type}
    </span>
  )
}

/* ---------------------------------------------------------------------- */
/*  MAIN PAGE                                                              */
/* ---------------------------------------------------------------------- */
export default function EmploymentExchange() {
  const { rows: listings, loading, add, update, remove } = useLiveRows('employmentListings')
  const [toast, setToast] = useState({ message: '', type: 'success' })
  const [showPost, setShowPost] = useState(false)
  const [form, setForm] = useState(emptyForm)
  const [search, setSearch] = useState('')
  const [filterType, setFilterType] = useState('All')
  const [filterArea, setFilterArea] = useState('All')
  const [filterStatus, setFilterStatus] = useState('All')

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

  const post = async (e) => {
    e.preventDefault()
    if (!form.text.trim() || !form.postedBy.trim()) return
    try {
      await add({ ...form, posted: new Date().toISOString().slice(0, 10), open: true })
      showToast('Requirement posted to the employment exchange')
      setShowPost(false)
      setForm(emptyForm)
    } catch (err) {
      showToast(err?.message || 'Post failed', 'error')
    }
  }

  const filtered = useMemo(() => {
    return listings.filter(l => {
      const q = search.toLowerCase()
      const matchesSearch = !q || `${l.text} ${l.postedBy} ${l.practiceArea}`.toLowerCase().includes(q)
      const matchesType = filterType === 'All' || l.type === filterType
      const matchesArea = filterArea === 'All' || l.practiceArea === filterArea
      const matchesStatus = filterStatus === 'All' || (filterStatus === 'Open' ? l.open !== false : l.open === false)
      return matchesSearch && matchesType && matchesArea && matchesStatus
    })
  }, [listings, search, filterType, filterArea, filterStatus])

  const stats = {
    total: listings.length,
    open: listings.filter(l => l.open !== false).length,
    senior: listings.filter(l => l.type === 'Senior Requirement').length,
    junior: listings.filter(l => l.type === 'Junior Requirement').length,
  }

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

      <div className="p-6 space-y-5">
        {/* STAT TILES */}
        <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
          <StatCard icon={Briefcase} label="Total Listings" value={stats.total} tone="red" />
          <StatCard icon={CheckCircle2} label="Open Listings" value={stats.open} />
          <StatCard icon={Crown} label="Senior Requirements" value={stats.senior} />
          <StatCard icon={Users2} label="Junior Requirements" value={stats.junior} />
        </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 listings..."
              className="bg-transparent outline-none text-sm w-full placeholder:text-gray-400"
            />
          </div>
          <select
            value={filterType}
            onChange={e => setFilterType(e.target.value)}
            className="text-sm rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-gray-700 outline-none"
          >
            <option value="All">All Types</option>
            {TYPES.map(t => <option key={t}>{t}</option>)}
          </select>
          <select
            value={filterArea}
            onChange={e => setFilterArea(e.target.value)}
            className="text-sm rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-gray-700 outline-none"
          >
            <option value="All">All Areas</option>
            {PRACTICE_AREAS.map(p => <option key={p}>{p}</option>)}
          </select>
          <div className="flex items-center gap-1 bg-gray-100 rounded-md p-1">
            {['All', 'Open', 'Filled'].map(f => (
              <button
                key={f}
                onClick={() => setFilterStatus(f)}
                className={`text-xs font-medium px-3 py-1.5 rounded-md transition-colors ${filterStatus === 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 {listings.length} listings</span>
        </div>

        {/* MAIN GRID */}
        <div className="grid grid-cols-1 gap-5 lg:grid-cols-[1fr_300px]">
          {/* LISTINGS */}
          <div className="space-y-3">
            {filtered.length === 0 && (
              <div className="bg-white border border-gray-200 rounded-lg py-14 text-center">
                <Briefcase size={28} className="mx-auto text-gray-300 mb-3" />
                <p className="text-sm text-gray-400">No listings match your filters.</p>
              </div>
            )}
            {filtered.map(item => (
              <div
                key={item.id}
                className={`bg-white border border-gray-200 rounded-lg p-4 flex items-start gap-3 transition-opacity ${item.open === false ? 'opacity-50' : ''}`}
              >
                <div className={`w-10 h-10 shrink-0 rounded-md flex items-center justify-center ${
                  item.type === 'Senior Requirement' ? 'bg-red-50 text-red-600' : 'bg-gray-100 text-gray-500'
                }`}>
                  <Briefcase size={16} />
                </div>

                <div className="flex-1 min-w-0">
                  <div className="flex items-start justify-between gap-2 flex-wrap">
                    <p className="text-sm font-semibold text-gray-900">{item.text}</p>
                    <TypePill type={item.type} />
                  </div>
                  <div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-gray-400">
                    <span>By <span className="text-gray-600 font-medium">{item.postedBy}</span></span>
                    <span>·</span>
                    <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-gray-100 text-gray-500 text-[11px]">
                      {item.practiceArea}
                    </span>
                    <span>·</span>
                    <span>{item.posted}</span>
                    <span>·</span>
                    <span className={`font-medium ${item.open !== false ? 'text-emerald-600' : 'text-gray-400'}`}>
                      {item.open !== false ? 'Open' : 'Filled'}
                    </span>
                  </div>
                </div>

                <div className="flex items-center gap-2 shrink-0 pl-2">
                  <Toggle
                    checked={item.open !== false}
                    onChange={async (v) => {
                      try {
                        await update(item.id, { ...item, open: v })
                        showToast(v ? 'Listing reopened' : 'Listing marked as filled', v ? 'success' : 'error')
                      } catch (err) {
                        showToast(err?.message || 'Update failed', 'error')
                      }
                    }}
                  />
                  <button
                    onClick={async () => {
                      try {
                        await remove(item.id)
                        showToast('Listing removed', 'error')
                      } catch (err) {
                        showToast(err?.message || 'Delete failed', 'error')
                      }
                    }}
                    className="w-7 h-7 rounded-md flex items-center justify-center text-gray-400 hover:bg-red-50 hover:text-red-600"
                    title="Remove listing"
                  >
                    <Trash2 size={13} />
                  </button>
                </div>
              </div>
            ))}
          </div>

          {/* SIDEBAR — Seniors Recruiting */}
          <div className="bg-white border border-gray-200 rounded-lg p-4 h-fit">
            <p className="mb-3 flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-gray-500">
              <Crown size={13} className="text-red-500" /> Seniors Currently Recruiting
            </p>
            <div className="space-y-3">
              {SENIOR_LEADERBOARD.map((s, i) => (
                <div key={s.senior} className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="flex h-6 w-6 items-center justify-center rounded-full bg-red-50 text-[11px] font-bold text-red-600">
                      {i + 1}
                    </span>
                    <div className="flex items-center gap-1.5">
                      <Users2 size={13} className="text-gray-400" />
                      <p className="text-sm text-gray-900">{s.senior}</p>
                    </div>
                  </div>
                  <span className="text-xs text-gray-400">{s.total} team</span>
                </div>
              ))}
            </div>

            <div className="mt-4 pt-4 border-t border-gray-100">
              <p className="text-xs font-semibold uppercase tracking-wide text-gray-500 mb-2">Practice Area Breakdown</p>
              {PRACTICE_AREAS.map(area => {
                const count = listings.filter(l => l.practiceArea === area && l.open !== false).length
                return count > 0 ? (
                  <div key={area} className="flex items-center gap-2 mb-2">
                    <div className="flex-1">
                      <div className="flex items-center justify-between mb-0.5">
                        <span className="text-xs text-gray-600">{area}</span>
                        <span className="text-xs font-semibold text-gray-900">{count}</span>
                      </div>
                      <div className="h-1.5 bg-gray-100 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-red-500 rounded-full"
                          style={{ width: `${(count / stats.open) * 100}%` }}
                        />
                      </div>
                    </div>
                  </div>
                ) : null
              })}
            </div>
          </div>
        </div>
      </div>

      {/* POST MODAL */}
      <Modal
        open={showPost}
        onClose={() => { setShowPost(false); setForm(emptyForm) }}
        title="Post Requirement"
        footer={
          <>
            <button onClick={() => { setShowPost(false); setForm(emptyForm) }} className="px-4 py-2 text-sm rounded-md text-gray-600 hover:bg-gray-100">
              Cancel
            </button>
            <button onClick={post} className="px-4 py-2 text-sm rounded-md bg-red-600 text-white hover:bg-red-500 font-medium">
              Post
            </button>
          </>
        }
      >
        <form onSubmit={post} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">Requirement</label>
            <input
              required
              value={form.text}
              onChange={e => setForm({ ...form, text: e.target.value })}
              className={fieldClass()}
              placeholder="e.g. 1 Civil Law Junior Required"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Type</label>
              <select value={form.type} onChange={e => setForm({ ...form, type: e.target.value })} className={fieldClass()}>
                {TYPES.map(t => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-500 mb-1">Practice Area</label>
              <select value={form.practiceArea} onChange={e => setForm({ ...form, practiceArea: e.target.value })} className={fieldClass()}>
                {PRACTICE_AREAS.map(p => <option key={p}>{p}</option>)}
              </select>
            </div>
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-500 mb-1">Posted By</label>
            <input
              required
              value={form.postedBy}
              onChange={e => setForm({ ...form, postedBy: e.target.value })}
              className={fieldClass()}
              placeholder="Your name"
            />
          </div>
          <div className="rounded-md bg-red-50 border border-red-100 px-4 py-3 text-xs text-red-700">
            This listing will be visible to all bar members and marked <strong>Open</strong> immediately after posting.
          </div>
        </form>
      </Modal>

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