'use client';

import React,{useEffect,useState} from 'react';
import {Plus,Pencil,Trash2,ClipboardList,ShieldCheck} from 'lucide-react';
import {apiRequest} from '../../../lib/api';
import {Badge} from '../../../components/Badge';
import {Button} from '../../../components/Button';
import {Modal} from '../../../components/Modal';

const blank={name:'',phone:'',password:''};
export default function ScorersAdminPage(){
 const [scorers,setScorers]=useState<any[]>([]),[loading,setLoading]=useState(true),[open,setOpen]=useState(false),[editing,setEditing]=useState<any>(null),[form,setForm]=useState(blank),[saving,setSaving]=useState(false),[historyOpen,setHistoryOpen]=useState(false),[selected,setSelected]=useState<any>(null),[history,setHistory]=useState<any[]>([]);
 const load=async()=>{try{setLoading(true);const r=await apiRequest('/users/scorers');setScorers(r.data||[])}catch(e){console.error(e)}finally{setLoading(false)}}; useEffect(()=>{load()},[]);
 const create=()=>{setEditing(null);setForm(blank);setOpen(true)}; const edit=(s:any)=>{setEditing(s);setForm({name:s.name||'',phone:s.phone||'',password:''});setOpen(true)};
 const save=async(e:React.FormEvent)=>{e.preventDefault();setSaving(true);try{if(editing){const body:any={name:form.name,phone:form.phone};if(form.password)body.password=form.password;await apiRequest(`/users/scorers/${editing._id}`,{method:'PATCH',body:JSON.stringify(body)})}else await apiRequest('/users/scorers',{method:'POST',body:JSON.stringify(form)});setOpen(false);await load()}catch(e:any){alert(e.message||'Unable to save scorer')}finally{setSaving(false)}};
 const toggle=async(s:any)=>{try{await apiRequest(`/users/scorers/${s._id}/status`,{method:'PATCH',body:JSON.stringify({status:s.status==='ACTIVE'?'INACTIVE':'ACTIVE'})});await load()}catch(e:any){alert(e.message||'Unable to change status')}};
 const del=async(s:any)=>{if(!confirm(`Delete scorer ${s.name}?`))return;try{await apiRequest(`/users/scorers/${s._id}`,{method:'DELETE'});await load()}catch(e:any){alert(e.message||'Unable to delete scorer')}};
 const assignments=async(s:any)=>{setSelected(s);setHistoryOpen(true);try{const r=await apiRequest(`/users/scorers/${s._id}/assignments`);setHistory(r.data||[])}catch(e){console.error(e)}};
 return <div className="admin-page space-y-6">
  <div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between"><div><div className="admin-kicker">Operations · Section 4</div><h1 className="admin-title">Scorer Management</h1><p className="admin-subtitle">Register scorers, manage credentials and inspect assignment history.</p></div><Button onClick={create} className="!bg-red-600 hover:!bg-red-500 gap-2"><Plus className="h-4 w-4"/> Register Scorer</Button></div>
  <div className="admin-panel overflow-hidden"><div className="flex items-center justify-between border-b border-white/5 px-5 py-4"><div><div className="text-sm font-extrabold text-white">Registered Scorers</div><div className="mt-1 text-[10px] text-zinc-600">Only assigned scorers can update match scoring.</div></div><ShieldCheck className="h-5 w-5 text-red-400"/></div><div className="overflow-x-auto"><table className="admin-table min-w-[780px]"><thead><tr><th>Scorer</th><th>Mobile</th><th>Status</th><th>Registered</th><th className="text-right">Actions</th></tr></thead><tbody>
   {loading?<tr><td colSpan={5} className="py-12 text-center text-zinc-600">Loading scorers…</td></tr>:scorers.length===0?<tr><td colSpan={5} className="py-12 text-center text-zinc-600">No scorers registered.</td></tr>:scorers.map(s=><tr key={s._id}><td><div className="font-bold text-white">{s.name}</div><div className="text-[9px] text-zinc-600">Official scorer</div></td><td className="font-mono">{s.phone}</td><td><Badge variant={s.status==='ACTIVE'?'emerald':'rose'}>{s.status}</Badge></td><td className="font-mono text-zinc-500">{new Date(s.createdAt).toLocaleDateString('en-IN')}</td><td><div className="flex justify-end gap-2"><button className="admin-action" onClick={()=>edit(s)}><Pencil className="h-3.5 w-3.5"/> Edit</button><button className="admin-action" onClick={()=>toggle(s)}>{s.status==='ACTIVE'?'Deactivate':'Activate'}</button><button className="admin-action" onClick={()=>assignments(s)}><ClipboardList className="h-3.5 w-3.5"/> Assignments</button><button className="admin-action red" onClick={()=>del(s)}><Trash2 className="h-3.5 w-3.5"/> Delete</button></div></td></tr>)}
  </tbody></table></div></div>
  <Modal isOpen={open} onClose={()=>setOpen(false)} title={editing?'Edit Scorer':'Register Scorer'}><form onSubmit={save} className="space-y-4"><div><label className="admin-label">Full Name *</label><input required className="admin-input" value={form.name} onChange={e=>setForm({...form,name:e.target.value})}/></div><div><label className="admin-label">Mobile Number *</label><input required inputMode="numeric" maxLength={15} className="admin-input font-mono" value={form.phone} onChange={e=>setForm({...form,phone:e.target.value.replace(/\D/g,'')})}/></div><div><label className="admin-label">{editing?'New Password · Optional':'Password *'}</label><input required={!editing} minLength={8} type="password" className="admin-input" value={form.password} onChange={e=>setForm({...form,password:e.target.value})}/></div><div className="flex justify-end gap-2 pt-2"><Button type="button" variant="ghost" onClick={()=>setOpen(false)}>Cancel</Button><Button type="submit" loading={saving} className="!bg-red-600 hover:!bg-red-500">{editing?'Save Changes':'Register Scorer'}</Button></div></form></Modal>
  <Modal isOpen={historyOpen} onClose={()=>setHistoryOpen(false)} title={`Assignments · ${selected?.name||''}`} maxWidth="max-w-2xl"><div className="space-y-3">{history.length===0?<div className="py-8 text-center text-xs text-zinc-600">No assignment history.</div>:history.map(h=><div key={h._id} className="rounded-xl border border-white/6 bg-black/15 p-4"><div className="flex items-center justify-between gap-3"><div className="font-bold text-white">{h.matchId?.title||'Match'}</div><Badge variant={h.action==='ASSIGNED'?'emerald':'rose'}>{h.action}</Badge></div><div className="mt-2 text-[10px] text-zinc-500">{h.matchId?.venue||'—'} · {h.matchId?.startTime?new Date(h.matchId.startTime).toLocaleString('en-IN'):''}</div>{h.note&&<div className="mt-1 text-[10px] text-zinc-600">{h.note}</div>}</div>)}</div></Modal>
 </div>
}
