import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Plus, Search, ShieldCheck } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import StatusPill from '@/components/workshop/StatusPill';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import OssiguardProfileForm from '@/components/ossiguard/OssiguardProfileForm';
import { ossiguardService, SAFETY_BANNER } from '@/services/ossiguardService';

export default function OssiguardLibrary() {
  const [items, setItems] = useState(null);
  const [editing, setEditing] = useState(null);
  const [search, setSearch] = useState('');

  const load = () => ossiguardService.list().then(setItems);
  useEffect(() => { load(); }, []);

  const shown = items ? items.filter((x) => `${x.profile_name} ${x.version} ${x.approval_status}`.toLowerCase().includes(search.toLowerCase())) : [];

  const save = async (f) => {
    if (editing?.id) await ossiguardService.update(editing, f, 'Ray');
    else await ossiguardService.create(f, 'Ray');
    setEditing(null);
    load();
  };

  return (
    <>
      <PageHeader
        eyebrow="Reusable connector system"
        title="Ossiguard Connector Library"
        description="SHiRE's proprietary cosmetic cover connector. Each profile preserves revision history — superseded revisions are never deleted."
        action={<div className="flex flex-wrap gap-2"><Link className="btn-primary" to="/ossiguard-connectors/new"><Plus />Connector Wizard</Link><button className="btn-secondary" onClick={() => setEditing({})}><Plus />Quick Profile</button></div>}
      />

      <div className="mb-4 rounded-lg border border-violet-400/30 bg-violet-400/5 p-3 text-xs text-violet-200">
        <ShieldCheck className="mr-1.5 inline h-4 w-4" />{SAFETY_BANNER}
      </div>

      {editing && (
        <div className="panel mb-6 p-6">
          <h2 className="section-title">{editing.id ? 'Edit Ossiguard Profile' : 'Create Ossiguard Profile'}</h2>
          <OssiguardProfileForm 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 Ossiguard profiles</span>
        <input className="workshop-input mt-0 pl-12" placeholder="Search profile name, version or approval status" value={search} onChange={(e) => setSearch(e.target.value)} />
      </label>

      {!items ? <LoadingPanel label="Loading Ossiguard profiles" /> : shown.length === 0 ? (
        <p className="text-sm text-slate-500">No Ossiguard profiles yet. Create one to get started.</p>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {shown.map((p) => (
            <Link key={p.uuid} to={`/ossiguard/${p.uuid}`} className="panel group block p-5 transition hover:border-shire-purple/40">
              <div className="mb-3 flex items-start justify-between">
                <div>
                  <h3 className="text-lg font-semibold text-white group-hover:text-violet-300">{p.profile_name}</h3>
                  <p className="text-xs text-slate-500">{p.version} · rev{p.connector_revision}</p>
                </div>
                <StatusPill tone={p.approval_status === 'Approved Connector Revision' ? 'green' : p.approval_status === 'Superseded' ? 'slate' : 'amber'}>
                  {p.approval_status}
                </StatusPill>
              </div>
              <dl className="space-y-1 text-xs text-slate-400">
                <div className="flex justify-between"><dt>Geometry</dt><dd className="text-slate-300">{p.geometry_status}</dd></div>
                <div className="flex justify-between"><dt>Attaches to</dt><dd className="text-slate-300">{p.attaches_to_component_label || 'Not set'}</dd></div>
                <div className="flex justify-between"><dt>Attachment points</dt><dd className="text-slate-300">{p.attachment_point_count || '—'}</dd></div>
                <div className="flex justify-between"><dt>CAD files</dt><dd className="text-slate-300">{[p.step_file_url, p.stl_file_url, p.three_mf_file_url].filter(Boolean).length || 'None'}</dd></div>
              </dl>
            </Link>
          ))}
        </div>
      )}
    </>
  );
}