import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { Plus, Search, Plug } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import ComponentCard from '@/components/components/ComponentCard';
import ComponentForm from '@/components/components/ComponentForm';
import { componentService } from '@/services/componentService';
export default function Components() { const [items,setItems]=useState([]); const [editing,setEditing]=useState(null); const [search,setSearch]=useState(''); const load=()=>componentService.list().then(setItems); useEffect(()=>{load()},[]); const shown=useMemo(()=>items.filter(x=>`${x.manufacturer} ${x.model} ${x.category}`.toLowerCase().includes(search.toLowerCase())),[items,search]); const save=async f=>{editing?.id?await componentService.update(editing,f,'Ray'):await componentService.create(f,'Ray');setEditing(null);load()}; const toggle=async x=>{x.record_state==='archived'?await componentService.restore(x):await componentService.archive(x);load()}; const copy=async x=>{await componentService.copy(x,'Ray');load()}; return <><PageHeader eyebrow="Verified reusable records" title="Component Library" description="Exact models only. Seed templates deliberately contain no invented manufacturer dimensions." action={<div className="flex flex-wrap gap-2"><Link className="btn-secondary" to="/ossiguard"><Plug/>Ossiguard Connectors</Link><button className="btn-primary" onClick={()=>setEditing({})}><Plus/>New component</button></div>}/>{editing&&<div className="panel mb-6 p-6"><ComponentForm initial={editing} onSave={save} onCancel={()=>setEditing(null)}/></div>}<label className="relative mb-6 block"><Search className="absolute left-4 top-3.5 h-5 w-5 text-slate-500"/><span className="sr-only">Search components</span><input className="workshop-input mt-0 pl-12" placeholder="Search manufacturer, exact model or category" value={search} onChange={e=>setSearch(e.target.value)}/></label><div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">{shown.map(x=><ComponentCard key={x.uuid} item={x} onEdit={setEditing} onCopy={copy} onToggle={toggle}/>)}</div></> }