import { Upload, Move, RotateCw, FlipHorizontal2, FlipVertical2, Crosshair, Layers, Palette, Sliders, Boxes, Layers2 } from 'lucide-react';
import CollapsibleSection from '@/components/app/CollapsibleSection';
import PromptForgePanel from '@/components/studio/PromptForgePanel';
import { Image as ContentImage } from '@/components/ui/image';

const PROJECTIONS = [
  ['planar', 'Planar', 'Real'],
  ['cylindrical', 'Cylindrical', 'Preview'],
  ['surface', 'Surface', 'Geometry Engine'],
  ['decal', 'Decal', 'Preview'],
  ['uv', 'UV', 'Geometry Engine'],
  ['wrap', 'Wrap', 'Preview']
];

function MeasurementInput({ label, value, onChange, min, max, step = 0.1, unit = 'mm' }) {
  return (
    <label className="block">
      <span className="flex items-center justify-between text-[11px] text-slate-400"><span>{label}</span><b className="mono text-slate-200">{(value ?? 0).toFixed(2)} {unit}</b></span>
      <div className="mt-1 flex items-center gap-2">
        <input type="range" min={min} max={max} step={step} value={value ?? 0} onChange={e => onChange(Number(e.target.value))} className="flex-1 accent-cyan-400" />
        <input type="number" step={step} min={min} max={max} value={Number((value ?? 0).toFixed(2))} onChange={e => onChange(Number(e.target.value))} className="field w-20 px-2 py-1 text-xs" />
      </div>
    </label>
  );
}

function SourceSection({ selected, asset, onUpload, onReplace, onRemove, onNavigate }) {
  return (
    <>
      <label className="block cursor-pointer rounded-lg border border-dashed border-white/15 bg-white/[0.02] p-3 text-center text-xs text-slate-400 transition hover:border-cyan-400/40 hover:text-cyan-200">
        <Upload size={15} className="mr-1.5 inline" />Upload image / drawing
        <input type="file" accept="image/*" className="hidden" onChange={e => { const f = e.target.files[0]; if (f) onUpload(f); }} />
      </label>
      <div className="flex flex-wrap gap-1.5">
        <button disabled={!selected} onClick={onReplace} className="chip">Replace source</button>
        <button disabled={!selected} onClick={onRemove} className="chip hover:border-red-400/40 hover:text-red-300">Remove source</button>
      </div>
      {asset && <div className="flex items-center gap-2 rounded-md border border-white/[0.06] bg-black/20 p-1.5"><ContentImage src={asset.processedFile || asset.originalFile} className="h-9 w-9 rounded" /><span className="mono truncate text-[10px] text-slate-400">{asset.width}×{asset.height}{asset.processedFile && ' · cleaned'}</span></div>}
    </>
  );
}

function TransformSection({ selected, onUpdate, lockAspect, onSetLockAspect }) {
  if (!selected) return <p className="text-xs text-slate-500">Select a layer to transform.</p>;
  const lock = lockAspect;
  const setScale = (v) => onUpdate(lock ? { scaleX: v, scaleY: v } : { scaleX: v });
  const setScaleY = (v) => onUpdate(lock ? { scaleX: v, scaleY: v } : { scaleY: v });
  return (
    <>
      <div className="grid grid-cols-3 gap-1.5">
        <button onClick={() => onUpdate({ positionX: (selected.positionX || 0) - 0.05 })} className="tool-button justify-center" title="Move left">←</button>
        <div className="grid grid-rows-2 gap-1">
          <button onClick={() => onUpdate({ positionY: (selected.positionY || 0) + 0.05 })} className="tool-button justify-center py-0.5" title="Move up">↑</button>
          <button onClick={() => onUpdate({ positionY: (selected.positionY || 0) - 0.05 })} className="tool-button justify-center py-0.5" title="Move down">↓</button>
        </div>
        <button onClick={() => onUpdate({ positionX: (selected.positionX || 0) + 0.05 })} className="tool-button justify-center" title="Move right">→</button>
      </div>
      <MeasurementInput label={lock ? 'Uniform scale' : 'Width scale'} value={Math.abs(selected.scaleX ?? 1)} onChange={setScale} min={0.1} max={3} step={0.05} unit="×" />
      {!lock && <MeasurementInput label="Height scale" value={Math.abs(selected.scaleY ?? 1)} onChange={setScaleY} min={0.1} max={3} step={0.05} unit="×" />}
      <label className="flex items-center gap-2 text-[11px] text-slate-400"><input type="checkbox" checked={!!lock} onChange={e => onSetLockAspect(e.target.checked)} className="h-3.5 w-3.5 accent-cyan-400" />Lock aspect ratio</label>
      <MeasurementInput label="Rotate" value={selected.rotation ?? 0} onChange={v => onUpdate({ rotation: v })} min={-180} max={180} step={1} unit="°" />
      <div className="flex gap-1.5">
        <button onClick={() => onUpdate({ mirrored: !selected.mirrored, scaleX: -Math.abs(selected.scaleX || 1) })} className="tool-button flex-1 justify-center" title="Mirror X"><FlipHorizontal2 size={13} /></button>
        <button onClick={() => onUpdate({ mirrored: !selected.mirrored, scaleY: -Math.abs(selected.scaleY || 1) })} className="tool-button flex-1 justify-center" title="Mirror Y"><FlipVertical2 size={13} /></button>
        <button onClick={() => onUpdate({ scaleX: -(selected.scaleX || 1), scaleY: -(selected.scaleY || 1), mirrored: !selected.mirrored })} className="tool-button flex-1 justify-center text-[10px]">XY</button>
      </div>
      <div className="flex gap-1.5">
        <button onClick={() => onUpdate({ positionX: 0, positionY: 0, scaleX: 1, scaleY: 1, rotation: 0 })} className="tool-button flex-1 justify-center"><RotateCw size={12} />Reset</button>
        <button onClick={() => onUpdate({ positionX: 0, positionY: 0 })} className="tool-button flex-1 justify-center"><Crosshair size={12} />Centre</button>
      </div>
    </>
  );
}

function AppearanceSection({ selected, asset, onUpdate, onUpdateAsset }) {
  if (!selected) return <p className="text-xs text-slate-500">Select a layer.</p>;
  const ps = asset?.processingSettings || {};
  const setPs = (patch) => onUpdateAsset(asset, { processingSettings: { ...ps, ...patch } });
  return (
    <>
      <MeasurementInput label="Opacity" value={selected.opacity ?? 1} onChange={v => onUpdate({ opacity: v })} min={0} max={1} step={0.05} unit="" />
      <label className="block text-[11px] text-slate-400">Colour<input type="color" defaultValue={ps.colour || '#22d3ee'} onBlur={e => setPs({ colour: e.target.value })} className="mt-1 h-7 w-full rounded border border-white/10 bg-transparent" /></label>
      <MeasurementInput label="Contrast" value={ps.contrast ?? 1} onChange={v => setPs({ contrast: v })} min={0} max={2} step={0.05} unit="×" />
      <MeasurementInput label="Brightness" value={ps.brightness ?? 1} onChange={v => setPs({ brightness: v })} min={0} max={2} step={0.05} unit="×" />
      <MeasurementInput label="Threshold" value={asset?.threshold ?? 0.5} onChange={v => onUpdateAsset(asset, { threshold: v })} min={0} max={1} step={0.05} unit="" />
      <label className="flex items-center gap-2 text-[11px] text-slate-400"><input type="checkbox" checked={!!asset?.inverted} onChange={e => onUpdateAsset(asset, { inverted: e.target.checked })} className="h-3.5 w-3.5 accent-cyan-400" />Invert</label>
      <MeasurementInput label="Smoothing" value={asset?.smoothing ?? 0.3} onChange={v => onUpdateAsset(asset, { smoothing: v })} min={0} max={1} step={0.05} unit="" />
      <MeasurementInput label="Detail preservation" value={ps.detail ?? 0.6} onChange={v => setPs({ detail: v })} min={0} max={1} step={0.05} unit="" />
      <label className="flex items-center gap-2 text-[11px] text-slate-400"><input type="checkbox" checked={!!ps.edgeCleanup} onChange={e => setPs({ edgeCleanup: e.target.checked })} className="h-3.5 w-3.5 accent-cyan-400" />Edge cleanup</label>
    </>
  );
}

const GEO_MODES = [
  ['colour_texture', 'Colour texture'], ['raised_emboss', 'Emboss'], ['engraving', 'Engrave'], ['sculpted_relief', 'Relief'], ['stencil', 'Stencil']
];

function GeometrySection({ project, selected, onUpdateProject, onUpdate }) {
  const mode = project?.applicationMode || 'colour_texture';
  const gs = project?.geometrySettings || {};
  const setGs = (patch) => onUpdateProject({ geometrySettings: { ...gs, ...patch } });
  return (
    <>
      <div className="flex flex-wrap gap-1.5">
        {GEO_MODES.map(([k, l]) => (
          <button key={k} onClick={() => onUpdateProject({ applicationMode: k })} className={`chip ${mode === k ? 'chip-active' : ''} ${(k === 'sculpted_relief' || k === 'stencil') ? 'border-amber-400/40 text-amber-200' : ''}`}>{l}</button>
        ))}
      </div>
      {mode === 'raised_emboss' && (<>
        <MeasurementInput label="Height" value={selected?.embossHeight ?? 1.2} onChange={v => onUpdate({ embossHeight: v })} min={0.4} max={4} />
        <MeasurementInput label="Bevel" value={gs.embossBevel ?? 0.3} onChange={v => setGs({ embossBevel: v })} min={0} max={1} />
        <MeasurementInput label="Smoothing" value={gs.embossSmooth ?? 0.4} onChange={v => setGs({ embossSmooth: v })} min={0} max={1} unit="" />
        <MeasurementInput label="Minimum feature" value={gs.embossMinFeature ?? 0.6} onChange={v => setGs({ embossMinFeature: v })} min={0.2} max={2} />
      </>)}
      {mode === 'engraving' && (<>
        <MeasurementInput label="Depth" value={selected?.engravingDepth ?? 0.8} onChange={v => onUpdate({ engravingDepth: v })} min={0.2} max={3} />
        <MeasurementInput label="Bevel" value={gs.engraveBevel ?? 0.3} onChange={v => setGs({ engraveBevel: v })} min={0} max={1} />
        <MeasurementInput label="Smoothing" value={gs.engraveSmooth ?? 0.4} onChange={v => setGs({ engraveSmooth: v })} min={0} max={1} unit="" />
        <MeasurementInput label="Minimum feature" value={gs.engraveMinFeature ?? 0.6} onChange={v => setGs({ engraveMinFeature: v })} min={0.2} max={2} />
      </>)}
      {mode === 'sculpted_relief' && (<>
        <MeasurementInput label="Relief strength" value={selected?.reliefStrength ?? 0.5} onChange={v => onUpdate({ reliefStrength: v })} min={0} max={1} unit="" />
        <MeasurementInput label="Height range" value={gs.reliefRange ?? 1.5} onChange={v => setGs({ reliefRange: v })} min={0.5} max={4} />
        <MeasurementInput label="Depth-map contrast" value={gs.reliefContrast ?? 1} onChange={v => setGs({ reliefContrast: v })} min={0} max={2} unit="×" />
        <MeasurementInput label="Surface blending" value={gs.reliefBlend ?? 0.4} onChange={v => setGs({ reliefBlend: v })} min={0} max={1} unit="" />
        <span className="sim-badge">Requires Geometry Engine</span>
      </>)}
      {mode === 'stencil' && (<>
        <MeasurementInput label="Cut depth" value={gs.stencilDepth ?? 1} onChange={v => setGs({ stencilDepth: v })} min={0.2} max={3} />
        <MeasurementInput label="Minimum bridge width" value={gs.stencilBridge ?? 0.8} onChange={v => setGs({ stencilBridge: v })} min={0.2} max={2} />
        <MeasurementInput label="Minimum opening" value={gs.stencilOpening ?? 0.6} onChange={v => setGs({ stencilOpening: v })} min={0.2} max={2} />
        <label className="flex items-center gap-2 text-[11px] text-slate-400"><input type="checkbox" checked={!!gs.stencilIslandRemoval} onChange={e => setGs({ stencilIslandRemoval: e.target.checked })} className="h-3.5 w-3.5 accent-cyan-400" />Automatic island removal</label>
        <span className="sim-badge">Requires Geometry Engine</span>
      </>)}
      {mode === 'colour_texture' && <p className="text-xs text-slate-500">Colour texture applies visual colour — no geometry change.</p>}
    </>
  );
}

function ProjectionSection({ selected, onUpdate }) {
  if (!selected) return <p className="text-xs text-slate-500">Select a layer.</p>;
  return (
    <div className="space-y-1.5">
      {PROJECTIONS.map(([k, l, tag]) => (
        <button key={k} onClick={() => onUpdate({ projectionMode: k })} className={`flex w-full items-center justify-between rounded-lg border px-2.5 py-1.5 text-left text-[11px] transition ${(selected.projectionMode || 'planar') === k ? 'border-cyan-400/50 bg-cyan-400/[0.08] text-cyan-100' : 'border-white/[0.06] text-slate-300 hover:bg-white/[0.03]'}`}>
          <span>{l}</span>
          <span className={`rounded px-1.5 py-0.5 text-[9px] uppercase ${tag === 'Real' ? 'text-emerald-300' : tag === 'Geometry Engine' ? 'text-amber-300' : 'text-violet-300'}`}>{tag}</span>
        </button>
      ))}
    </div>
  );
}

function LayerSection({ selected, onUpdate, onDuplicate, onDelete, onMove, onUpdateAsset, asset }) {
  if (!selected) return <p className="text-xs text-slate-500">Select a layer.</p>;
  const ps = asset?.processingSettings || {};
  const setPs = (patch) => onUpdateAsset(asset, { processingSettings: { ...ps, ...patch } });
  return (
    <>
      <label className="block text-[11px] text-slate-400">Blending mode
        <select value={ps.blendMode || 'normal'} onChange={e => setPs({ blendMode: e.target.value })} className="field mt-1 py-1 text-xs">
          <option value="normal">Normal</option><option value="multiply">Multiply</option><option value="overlay">Overlay</option><option value="screen">Screen</option>
        </select>
      </label>
      <label className="flex items-center gap-2 text-[11px] text-slate-400"><input type="checkbox" checked={!!ps.preserveDetails} onChange={e => setPs({ preserveDetails: e.target.checked })} className="h-3.5 w-3.5 accent-cyan-400" />Preserve details</label>
      <label className="flex items-center gap-2 text-[11px] text-slate-400"><input type="checkbox" checked={!!ps.clipToZone} onChange={e => setPs({ clipToZone: e.target.checked })} className="h-3.5 w-3.5 accent-cyan-400" />Clip to decoration zone</label>
      <div className="flex flex-wrap gap-1.5">
        <button onClick={() => onMove(selected, -1)} className="tool-button">↑ Reorder</button>
        <button onClick={() => onMove(selected, 1)} className="tool-button">↓ Reorder</button>
        <button onClick={() => onUpdate(selected, { locked: !selected.locked })} className="tool-button">{selected.locked ? '🔒 Lock' : 'Unlock'}</button>
        <button onClick={() => onUpdate(selected, { visible: !selected.visible })} className="tool-button">{selected.visible ? '👁 Hide' : 'Show'}</button>
        <button onClick={() => onDuplicate(selected)} className="tool-button">Duplicate</button>
        <button onClick={() => onDelete(selected)} className="tool-button hover:border-red-400/40 hover:text-red-300">Delete</button>
      </div>
    </>
  );
}

export default function ArtworkToolsPanel({ project, selected, asset, onUpdateLayer, onUpdateProject, onUpdateAsset, onUpload, onReplace, onRemove, onDuplicate, onMove, onDelete, onNavigate, projectId, onApplyConcept, onOpenFull, lockAspect, onSetLockAspect }) {
  return (
    <div className="flex h-full flex-col overflow-hidden rounded-2xl border border-white/[0.06] bg-[#0d1117]">
      <div className="flex items-center gap-2 border-b border-white/[0.06] px-4 py-3">
        <Layers size={15} className="text-cyan-300" />
        <h2 className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-200">Artwork tools</h2>
      </div>
      <div className="flex-1 overflow-y-auto px-4">
        <CollapsibleSection title="Artwork source" icon={Upload}><SourceSection selected={selected} asset={asset} onUpload={onUpload} onReplace={onReplace} onRemove={onRemove} onNavigate={onNavigate} /></CollapsibleSection>
        <PromptForgePanel projectId={projectId} onApplyConcept={onApplyConcept} onOpenFull={onOpenFull} />
        <CollapsibleSection title="Transform" icon={Move}><TransformSection selected={selected} onUpdate={(c) => onUpdateLayer(selected, c)} lockAspect={lockAspect} onSetLockAspect={onSetLockAspect} /></CollapsibleSection>
        <CollapsibleSection title="Appearance" icon={Palette} defaultOpen={false}><AppearanceSection selected={selected} asset={asset} onUpdate={(c) => onUpdateLayer(selected, c)} onUpdateAsset={onUpdateAsset} /></CollapsibleSection>
        <CollapsibleSection title="Geometry" icon={Boxes}><GeometrySection project={project} selected={selected} onUpdateProject={onUpdateProject} onUpdate={(c) => onUpdateLayer(selected, c)} /></CollapsibleSection>
        <CollapsibleSection title="Projection" icon={Sliders} defaultOpen={false}><ProjectionSection selected={selected} onUpdate={(c) => onUpdateLayer(selected, c)} /></CollapsibleSection>
        <CollapsibleSection title="Layer" icon={Layers2} defaultOpen={false}><LayerSection selected={selected} onUpdate={onUpdateLayer} onDuplicate={onDuplicate} onDelete={onDelete} onMove={onMove} onUpdateAsset={onUpdateAsset} asset={asset} /></CollapsibleSection>
      </div>
    </div>
  );
}