import { useEffect, useState } from 'react';
import { Upload, Box } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import PageHeader from '@/components/app/PageHeader';
import CoverCard from '@/components/covers/CoverCard';
import { useExperienceMode } from '@/lib/ExperienceMode';

export default function CoverLibrary() {
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const [covers, setCovers] = useState([]);
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({ name: '', version: '1.0', limbType: 'leg', side: 'left', connectorType: '', ossiguardProfile: '', validationStatus: 'validated' });

  const load = () => base44.entities.CoverModel.filter({ active: true }, '-updated_date')
    .then(res => setCovers(Array.isArray(res) ? res : []))
    .catch(() => setCovers([]));
  useEffect(() => { load(); }, []);

  const upload = async e => {
    const file = e.target.files[0];
    if (!file) return;
    setBusy(true);
    const ext = file.name.split('.').pop().toLowerCase();
    const fmt = { stl: 'stl', obj: 'obj', glb: 'glb' }[ext];
    if (!fmt) { setBusy(false); alert('Unsupported cover format. Use STL, OBJ or GLB.'); return; }
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      await base44.entities.CoverModel.create({
        ...form, name: form.name || file.name.replace(/\.[^.]+$/, ''),
        sourceFile: file_url, sourceFormat: fmt, boundingBox: null,
        protectedZones: [], decorationZones: [], brandingZones: [], active: true
      });
      setForm({ ...form, name: '' });
      load();
    } catch (err) {
      alert(`Could not upload cover. ${err?.message || ''}`);
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <PageHeader eyebrow="Covers" title={guided ? 'Covers' : 'Cover library'} description={guided ? 'Your available prosthetic covers. Add a new cover by uploading an STL, OBJ or GLB file.' : 'Validated LimbForge cover definitions. Upload STL, OBJ or GLB cover files — bounding box and protected zones are finalised when the cover is loaded in the 3D viewer.'} />
      <div className="grid gap-5 xl:grid-cols-[1fr_380px]">
        <div className="grid gap-4 sm:grid-cols-2">
          {covers.map(c => <CoverCard key={c.id} cover={c} />)}
          {!covers.length && <div className="panel empty sm:col-span-2">No covers yet. Upload a validated cover file on the right.</div>}
        </div>
        <section className="panel h-fit">
          <h2 className="section-title"><Upload size={18} />Upload cover</h2>
          <label className="form-label">Name<input className="field" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} /></label>
          <div className="grid grid-cols-2 gap-3">
            <label className="form-label">Limb<select className="field" value={form.limbType} onChange={e => setForm({ ...form, limbType: e.target.value })}><option value="leg">Leg</option><option value="arm">Arm</option></select></label>
            <label className="form-label">Side<select className="field" value={form.side} onChange={e => setForm({ ...form, side: e.target.value })}><option value="left">Left</option><option value="right">Right</option></select></label>
            {!guided && (<>
              <label className="form-label">Version<input className="field" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })} /></label>
              <label className="form-label">Validation<select className="field" value={form.validationStatus} onChange={e => setForm({ ...form, validationStatus: e.target.value })}><option value="validated">Validated</option><option value="warning">Warning</option><option value="failed">Failed</option></select></label>
              <label className="form-label">Connector type<input className="field" value={form.connectorType} onChange={e => setForm({ ...form, connectorType: e.target.value })} /></label>
              <label className="form-label">Ossiguard profile<input className="field" value={form.ossiguardProfile} onChange={e => setForm({ ...form, ossiguardProfile: e.target.value })} /></label>
            </>)}
          </div>
          <label className="mt-4 block cursor-pointer">
            <div className="viewport-grid grid place-items-center rounded-xl border border-dashed border-white/15 p-8 text-center">
              <Box className="mb-2 text-cyan-300" />
              <b>{busy ? 'Uploading…' : 'Choose STL / OBJ / GLB'}</b>
              <p className="mt-1 text-xs text-slate-500">Temporary Base44 prototype storage</p>
            </div>
            <input type="file" accept=".stl,.obj,.glb" onChange={upload} className="hidden" />
          </label>
        </section>
      </div>
    </>
  );
}