import { Eye, EyeOff, Lock, ArrowUp, ArrowDown, Plus, MoreVertical, ShieldCheck, ShieldAlert, Activity } from 'lucide-react';
import { Image as ContentImage } from '@/components/ui/image';
import CollapsibleSection from '@/components/app/CollapsibleSection';

const STANDARD_ZONES = ['Structural integrity', 'Connector interface', 'Ossiguard', 'Edge clearance', 'Hardware clearance', 'Skin exclusion', 'Stoma exclusion', 'Implant & abutment', 'Service access'];
const zoneStatus = ['pass', 'warning', 'not_checked'];
const zoneDot = { pass: 'bg-emerald-400', warning: 'bg-amber-400', not_checked: 'bg-slate-600' };

const GEO_LABEL = { colour_texture: 'Colour', raised_emboss: 'Emboss', engraving: 'Engrave', sculpted_relief: 'Relief', stencil: 'Stencil' };

function LayerRow({ layer, selected, asset, onSelect, onUpdate, onMove, onDelete, onDuplicate }) {
  return (
    <div onClick={() => onSelect(layer)} className={`group flex items-center gap-2 rounded-lg border p-2 transition ${selected?.id === layer.id ? 'border-cyan-400/50 bg-cyan-400/[0.08]' : 'border-white/[0.06] hover:bg-white/[0.03]'}`}>
      <span className="cursor-grab text-slate-600 hover:text-slate-400">⠿</span>
      <div className="grid h-9 w-9 place-items-center overflow-hidden rounded border border-white/10 bg-black/30">
        {asset?.originalFile ? <ContentImage src={asset.originalFile} className="h-full w-full" /> : <span className="text-[9px] text-slate-600">—</span>}
      </div>
      <div className="min-w-0 flex-1">
        <p className={`truncate text-[12px] font-medium ${selected?.id === layer.id ? 'text-cyan-100' : 'text-slate-200'}`}>{layer.name}</p>
        <p className="text-[10px] text-slate-500">{layer.embossHeight ? 'Emboss' : layer.engravingDepth ? 'Engrave' : 'Colour'} · {layer.embossHeight ? `E ${layer.embossHeight}mm` : layer.engravingDepth ? `D ${layer.engravingDepth}mm` : '—'} · {Math.round((layer.opacity ?? 1) * 100)}%</p>
      </div>
      <button onClick={e => { e.stopPropagation(); onMove(layer, -1); }} className="text-slate-600 hover:text-cyan-300"><ArrowUp size={13} /></button>
      <button onClick={e => { e.stopPropagation(); onMove(layer, 1); }} className="text-slate-600 hover:text-cyan-300"><ArrowDown size={13} /></button>
      <button onClick={e => { e.stopPropagation(); onUpdate(layer, { visible: !layer.visible }); }} className="text-slate-500 hover:text-white">{layer.visible ? <Eye size={14} /> : <EyeOff size={14} />}</button>
      <button onClick={e => { e.stopPropagation(); onUpdate(layer, { locked: !layer.locked }); }} className="text-slate-500 hover:text-white">{layer.locked ? <Lock size={14} className="text-amber-300" /> : <Lock size={14} className="opacity-40" />}</button>
    </div>
  );
}

const QUICK_CHECKS = [
  ['Artwork resolution', 'pass'], ['Minimum feature size', 'simulation_only'], ['Curve continuity', 'warning'],
  ['Connector clearance', 'simulation_only'], ['Emboss limit', 'pass'], ['Engraving limit', 'pass'],
  ['Protected-zone overlap', 'not_checked'], ['SHiRE branding', 'pass'], ['Print readiness', 'simulation_only'], ['Final clearance check', 'not_checked']
];
const checkIcon = { pass: '✓', warning: '!', fail: '✕', not_checked: '•', simulation_only: '⊙' };
const checkCls = { pass: 'text-emerald-300', warning: 'text-amber-300', fail: 'text-red-300', not_checked: 'text-slate-500', simulation_only: 'text-violet-300' };

export default function StudioRightPanel({ project, cover, layers, selected, assets, onSelect, onUpdateLayer, onMove, onDuplicate, onDelete, onAddLayer, protectedVisible, onToggleProtected, onNavigate }) {
  const safeLayers = Array.isArray(layers) ? layers : [];
  const safeAssets = Array.isArray(assets) ? assets : [];
  const safeProtectedVisible = Array.isArray(protectedVisible) ? protectedVisible : [];
  const assetFor = (l) => safeAssets.find(a => a.id === l?.artworkAssetId);
  const zones = (Array.isArray(cover?.protectedZones) && cover.protectedZones.length) ? cover.protectedZones : STANDARD_ZONES.map(name => ({ name, status: 'not_checked' }));

  return (
    <div className="flex h-full flex-col overflow-hidden rounded-2xl border border-white/[0.06] bg-[#0d1117]">
      <div className="flex items-center justify-between border-b border-white/[0.06] px-4 py-3">
        <h2 className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-200">Layers & validation</h2>
        <button onClick={onAddLayer} className="icon-button" title="Add layer"><Plus size={15} /></button>
      </div>
      <div className="flex-1 overflow-y-auto px-4">
        <CollapsibleSection title="Artwork layers" icon={Plus} right={<span className="mono text-[10px] text-slate-500">{safeLayers.length}</span>}>
          <div className="space-y-1.5">
            {safeLayers.map(l => <LayerRow key={l.id} layer={l} selected={selected} asset={assetFor(l)} onSelect={onSelect} onUpdate={onUpdateLayer} onMove={onMove} onDelete={onDelete} onDuplicate={onDuplicate} />)}
            {!safeLayers.length && <p className="py-4 text-center text-xs text-slate-500">No layers yet.</p>}
          </div>
        </CollapsibleSection>

        <CollapsibleSection title="Protected zones" icon={ShieldAlert}>
          <div className="space-y-1.5">
            {zones.map((z, i) => {
              const st = z.status || 'not_checked';
              const visible = safeProtectedVisible.includes(i);
              return (
                <div key={i} className="flex items-center gap-2 rounded-lg border border-white/[0.06] bg-black/20 p-2">
                  <span className={`h-2 w-2 rounded-sm ${zoneDot[st] || zoneDot.not_checked}`} />
                  <span className="min-w-0 flex-1 truncate text-[11px] text-slate-300">{z.name}</span>
                  <button onClick={() => onToggleProtected(i)} className={`tool-rail-btn h-6 w-6 ${visible ? 'active' : ''}`} title="Toggle highlight"><Eye size={11} /></button>
                </div>
              );
            })}
          </div>
          <div className="mt-2 flex flex-wrap gap-1.5 text-[9px]">
            <span className="flex items-center gap-1 text-emerald-300"><span className="h-1.5 w-1.5 rounded-sm bg-emerald-400" />Pass</span>
            <span className="flex items-center gap-1 text-amber-300"><span className="h-1.5 w-1.5 rounded-sm bg-amber-400" />Warning</span>
            <span className="flex items-center gap-1 text-slate-500"><span className="h-1.5 w-1.5 rounded-sm bg-slate-600" />Not checked</span>
          </div>
        </CollapsibleSection>

        <CollapsibleSection title="SHiRE branding zone" icon={ShieldCheck}>
          <div className="flex items-center justify-between rounded-lg border border-emerald-400/20 bg-emerald-400/[0.06] p-2.5">
            <div><p className="text-[12px] font-medium text-slate-200">Logo area · {cover?.brandingZones?.[0]?.location || 'Right lateral'}</p><p className="mt-0.5 text-[10px] text-slate-500">Approved alternative zones only · not removable before approval</p></div>
            <ShieldCheck size={18} className="text-emerald-400" />
          </div>
        </CollapsibleSection>

        <CollapsibleSection title="Quick validation" icon={Activity}>
          <div className="space-y-1">
            {QUICK_CHECKS.map(([n, st]) => (
              <div key={n} className="flex items-center gap-2 rounded border border-white/[0.05] bg-black/15 px-2 py-1.5">
                <span className={`text-xs font-bold ${checkCls[st]}`}>{checkIcon[st]}</span>
                <span className="min-w-0 flex-1 truncate text-[11px] text-slate-300">{n}</span>
                {st === 'simulation_only' ? <span className="sim-badge">Sim</span> : <span className={`text-[10px] capitalize ${checkCls[st]}`}>{st.replace('_', ' ')}</span>}
              </div>
            ))}
          </div>
          <div className="mt-3 flex gap-2">
            <button onClick={() => onNavigate('/validation')} className="btn-secondary flex-1 text-xs">Run all</button>
            <button onClick={() => onNavigate('/validation')} className="btn-primary flex-1 text-xs">Open validation</button>
          </div>
        </CollapsibleSection>
      </div>
    </div>
  );
}