import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { ArrowRight, Upload, Loader2, Layers, Sliders, Palette, Wand2 } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import PageHeader from '@/components/app/PageHeader';
import CoverCard from '@/components/covers/CoverCard';
import CoverViewer from '@/components/studio/CoverViewer';
import { Image as ContentImage } from '@/components/ui/image';
import { useExperienceMode } from '@/lib/ExperienceMode';

const loadImageDims = (url) => new Promise((res) => {
  const img = new Image();
  img.onload = () => res({ w: img.naturalWidth, h: img.naturalHeight });
  img.onerror = () => res({ w: 1024, h: 1024 });
  img.src = url;
});

const modes = [
  ['colour_texture', 'Colour texture', 'Apply the image as a surface colour texture.'],
  ['raised_emboss', 'Emboss', 'Use image luminance to raise surface detail.'],
  ['engraving', 'Engraving', 'Use image luminance to cut recessed detail.'],
  ['sculpted_relief', 'Relief', 'Advanced — geometry engine required.'],
  ['stencil', 'Stencil', 'Advanced — geometry engine required.']
];

const simpleModes = modes.slice(0, 3);
const advancedModes = modes.slice(3);

export default function ImageApply() {
  const [params] = useSearchParams();
  const projectId = params.get('project');
  const navigate = useNavigate();
  const { mode } = useExperienceMode();
  const guided = mode === 'guided';
  const [covers, setCovers] = useState([]);
  const [cover, setCover] = useState(null);
  const [project, setProject] = useState(null);
  const [name, setName] = useState('');
  const [asset, setAsset] = useState(null);
  const [modeVal, setMode] = useState('colour_texture');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (projectId) {
      Promise.all([
        base44.entities.CoverCanvasProject.get(projectId).catch(() => null),
        base44.entities.ArtworkAsset.filter({ projectId }).catch(() => [])
      ]).then(async ([p, assets]) => {
        setProject(p);
        const safeAssets = Array.isArray(assets) ? assets : [];
        if (safeAssets[0]) setAsset(safeAssets[0]);
        if (p?.coverModelId) { try { setCover(await base44.entities.CoverModel.get(p.coverModelId)); } catch { setCover(null); } }
      }).catch(() => {});
    } else {
      base44.entities.CoverModel.filter({ active: true, validationStatus: 'validated' })
        .then(res => setCovers(Array.isArray(res) ? res : []))
        .catch(() => setCovers([]));
    }
  }, [projectId]);

  const upload = async e => {
    const file = e.target.files[0];
    if (!file) return;
    setBusy(true); setError(null);
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      const dims = await loadImageDims(file_url);
      if (projectId) {
        if (asset?.id) {
          const a = await base44.entities.ArtworkAsset.update(asset.id, { originalFile: file_url, width: dims.w, height: dims.h });
          setAsset(a);
        } else {
          const a = await base44.entities.ArtworkAsset.create({ projectId, originalFile: file_url, width: dims.w, height: dims.h, processingSettings: {} });
          setAsset(a);
        }
      } else {
        // Hold locally until a project exists — no orphaned "pending" records.
        setAsset({ file_url, width: dims.w, height: dims.h });
      }
    } catch (err) {
      setError(`Could not upload your file. ${err?.message || ''}`);
    } finally {
      setBusy(false);
    }
  };

  const create = async () => {
    if (!cover || !asset) return;
    setBusy(true); setError(null);
    try {
      const user = await base44.auth.me();
      const project = await base44.entities.CoverCanvasProject.create({
        name: name || `${cover.name} image apply`, owner: user.id, coverModelId: cover.id,
        status: 'studio', inputMethod: 'image_apply', applicationMode: modeVal,
        validationStatus: 'not_checked', shireVaultPath: `/SHiRELimbs/CoverCanvas/${Date.now()}`,
        artworkLayers: [], geometrySettings: {}, experienceMode: mode
      });
      let assetId = asset.id;
      if (!assetId) {
        const a = await base44.entities.ArtworkAsset.create({ projectId: project.id, originalFile: asset.file_url, width: asset.width, height: asset.height, processingSettings: {} });
        assetId = a.id;
      }
      await base44.entities.ArtworkLayer.create({
        projectId: project.id, artworkAssetId: assetId, name: (asset.originalFile || asset.file_url || 'image').split('/').pop(),
        order: 0, visible: true, locked: false, positionX: 0, positionY: 0, scaleX: 1, scaleY: 1,
        rotation: 0, mirrored: false, projectionMode: 'planar', opacity: 1
      });
      navigate(`/studio?project=${project.id}`);
    } catch (err) {
      setError(`Could not create your project. ${err?.message || ''}`);
    } finally {
      setBusy(false);
    }
  };

  const cont = async () => {
    if (projectId) {
      try { await base44.entities.CoverCanvasProject.update(projectId, { applicationMode: modeVal, status: 'studio' }); navigate(`/studio?project=${projectId}`); }
      catch (e) { setError(`Could not continue. ${e?.message || ''}`); }
    } else {
      create();
    }
  };

  const EffectChoice = ({ list }) => list.map(([k, l, d]) => {
    const isAdv = k === 'sculpted_relief' || k === 'stencil';
    return (
      <button key={k} onClick={() => setMode(k)} disabled={guided && isAdv}
        className={`flex w-full items-start gap-3 rounded-lg border p-3 text-left transition ${modeVal === k ? 'border-cyan-400/50 bg-cyan-400/[0.08]' : isAdv ? 'border-amber-400/30 opacity-70' : 'border-white/[0.06] hover:bg-white/[0.03]'}`}>
        <span className={`mt-1 h-3 w-3 rounded-full ${modeVal === k ? 'bg-cyan-400 shadow-[0_0_8px_rgba(34,211,238,0.6)]' : 'bg-white/15'}`} />
        <span><b className="block text-sm text-white">{l}{isAdv && <span className="ml-1 text-[9px] uppercase text-amber-300">adv</span>}</b><span className="text-xs text-slate-400">{d}</span></span>
      </button>
    );
  });

  if (guided) {
    return (
      <>
        <PageHeader eyebrow="Add your image" title="Image Apply" description="Upload an image and choose how it becomes part of your cover. Cut-out and Sculpted effects need the Geometry Engine." />
        <div className="grid gap-5 xl:grid-cols-[1fr_360px]">
          <section className="panel">
            <h2 className="section-title"><Layers size={16} />Your image</h2>
            <div className="viewport-grid relative grid min-h-[360px] place-items-center overflow-hidden rounded-2xl border border-dashed border-white/15">
              {asset ? <ContentImage src={asset.originalFile || asset.file_url} alt="Uploaded" fittingType="fit" className="max-h-[360px] w-full" /> : (
                <label className="cursor-pointer text-center">
                  <Upload className="mx-auto mb-3 text-cyan-300" />
                  <b>{busy ? 'Uploading…' : 'Choose image'}</b>
                  <p className="mt-2 text-xs text-slate-500">PNG · JPG · JPEG · WEBP · SVG</p>
                  <input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" onChange={upload} className="hidden" />
                </label>
              )}
            </div>
            {asset && <p className="mono mt-3 text-xs text-slate-500">{asset.width}×{asset.height}px</p>}
            {error && <div className="warning-box mt-3">{error}</div>}
          </section>
          <aside className="panel h-fit">
            <h2 className="section-title"><Sliders size={16} />Choose an effect</h2>
            <div className="space-y-2"><EffectChoice list={simpleModes} /></div>
            <div className="mt-4 space-y-2">
              <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-500">Advanced (needs Geometry Engine)</p>
              <EffectChoice list={advancedModes} />
            </div>
            {!projectId && (
              <>
                <h3 className="mb-2 mt-5 text-xs font-semibold uppercase tracking-wider text-slate-400"><Palette size={13} className="inline" /> Project & cover</h3>
                <label className="form-label">Name<input className="field" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Floral left leg cover" /></label>
                <div className="grid max-h-60 gap-3 overflow-y-auto sm:grid-cols-2">
                  {covers.map(c => <CoverCard key={c.id} cover={c} selected={cover?.id === c.id} onSelect={setCover} />)}
                </div>
                {!covers.length && <div className="empty">No validated covers. Create or import one in the Cover Library.</div>}
              </>
            )}
          </aside>
        </div>
        <div className="sticky bottom-4 mt-6 flex justify-end">
          <button disabled={!asset || (projectId ? false : !cover) || busy} onClick={cont} className="btn-primary">{busy ? <Loader2 size={17} className="animate-spin" /> : <Wand2 size={17} />}Open 3D Studio<ArrowRight size={17} /></button>
        </div>
      </>
    );
  }

  return (
    <>
      <PageHeader eyebrow="Input · Image Apply" title="Image Apply" description="Upload an image and apply it as a colour texture, emboss, engraving or stencil. Final decoration geometry is produced by the LimbForge Geometry Engine." />

      <div className="grid gap-4 2xl:grid-cols-[1.4fr_1fr_320px]">
        <section className="panel">
          <h2 className="section-title"><Layers size={16} />Artwork canvas</h2>
          <div className="viewport-grid relative grid min-h-[420px] place-items-center overflow-hidden rounded-2xl border border-dashed border-white/15">
            {asset ? <ContentImage src={asset.originalFile || asset.file_url} alt="Uploaded" fittingType="fit" className="max-h-[420px] w-full" /> : (
              <label className="cursor-pointer text-center">
                <Upload className="mx-auto mb-3 text-cyan-300" />
                <b>{busy ? 'Uploading…' : 'Choose image'}</b>
                <p className="mt-2 text-xs text-slate-500">PNG · JPG · JPEG · WEBP · SVG — temporary Base44 prototype storage</p>
                <input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" onChange={upload} className="hidden" />
              </label>
            )}
            <div className="scanline" />
          </div>
          {asset && <p className="mono mt-3 text-xs text-slate-500">{asset.width}×{asset.height}px · prototype storage only</p>}
        </section>

        <section className="panel">
          <h2 className="section-title">Live cover preview</h2>
          <div className="h-[300px]"><CoverViewer cover={cover} mode="studio" /></div>
          <div className="mt-4 grid grid-cols-2 gap-3">
            <div className="readout"><span className="readout-label">Width</span><span className="readout-value mono">{asset ? `${asset.width}px` : '—'}</span></div>
            <div className="readout"><span className="readout-label">Height</span><span className="readout-value mono">{asset ? `${asset.height}px` : '—'}</span></div>
          </div>
        </section>

        <aside className="panel h-fit">
          <h2 className="section-title"><Sliders size={16} />Application mode</h2>
          <div className="space-y-2"><EffectChoice list={modes} /></div>
          {!projectId && (
            <>
              <h3 className="mb-2 mt-5 text-xs font-semibold uppercase tracking-wider text-slate-400"><Palette size={13} className="inline" /> Project & cover</h3>
              <label className="form-label">Name<input className="field" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Floral left leg cover" /></label>
              <div className="grid max-h-60 gap-3 overflow-y-auto sm:grid-cols-2">
                {covers.map(c => <CoverCard key={c.id} cover={c} selected={cover?.id === c.id} onSelect={setCover} />)}
              </div>
              {!covers.length && <div className="empty">No validated covers. Create or import one in the Cover Library.</div>}
            </>
          )}
        </aside>
      </div>

      <div className="sticky bottom-4 mt-6 flex justify-end">
        <button disabled={!asset || (projectId ? false : !cover) || busy} onClick={cont} className="btn-primary">{busy ? <Loader2 size={17} className="animate-spin" /> : <Wand2 size={17} />}Open 3D Studio<ArrowRight size={17} /></button>
      </div>
    </>
  );
}