"use client";
import React, { useState, useCallback } from "react";
import Cropper from "react-easy-crop";

const RATIOS = [
  { label: "Hero Banner (Ultra Wide)", value: 21 / 9, text: "21/9" },
  { label: "News Feed (Widescreen)", value: 16 / 9, text: "16/9" },
  { label: "Profile / Post (Square)", value: 1 / 1, text: "1/1" },
];

export default function FullPageEditor() {
  const [image, setImage] = useState<string | null>(null);
  const [crops, setCrops] = useState<Record<string, any>>(
    RATIOS.reduce((acc, r) => ({ ...acc, [r.text]: { x: 0, y: 0, zoom: 1 } }), {})
  );
  const [completedCrops, setCompletedCrops] = useState<Record<string, any>>({});
  const [isExporting, setIsExporting] = useState(false);
  const [results, setResults] = useState<Record<string, string>>({});

  const onSelectFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const reader = new FileReader();
      reader.onload = () => setImage(reader.result as string);
      reader.readAsDataURL(e.target.files[0]);
    }
  };

  const handleExport = async () => {
    setIsExporting(true);
    const bundle: Record<string, string> = {};
    for (const ratio of RATIOS) {
      const crop = completedCrops[ratio.text];
      if (crop) bundle[ratio.text] = await getCroppedImg(image!, crop);
    }
    setResults(bundle);
    setIsExporting(false);
  };

  return (
    <div className="min-h-screen bg-zinc-950 text-zinc-100 font-sans selection:bg-indigo-500">
      {/* 1. Global Navigation */}
      <nav className="sticky top-0 z-50 border-b border-zinc-800 bg-zinc-950/80 backdrop-blur-md px-8 py-4 flex items-center justify-between">
        <div className="flex items-center gap-4">
          <div className="bg-indigo-600 p-2 rounded-lg font-black text-xs">FIX</div>
          <h1 className="text-lg font-bold tracking-tighter">IMAGE FRAMER <span className="text-zinc-500 font-medium text-sm ml-2">PRO v3.0</span></h1>
        </div>
        
        <div className="flex gap-4">
          <label className="cursor-pointer bg-zinc-800 hover:bg-zinc-700 text-sm font-bold px-5 py-2 rounded-full transition-all border border-zinc-700">
            {image ? "New Photo" : "Upload Source"}
            <input type="file" accept="image/*" className="hidden" onChange={onSelectFile} />
          </label>
          {image && (
            <button 
              onClick={handleExport}
              className="bg-indigo-600 hover:bg-indigo-500 text-white text-sm font-bold px-8 py-2 rounded-full shadow-lg shadow-indigo-900/20 transition-all active:scale-95"
            >
              {isExporting ? "Processing..." : "Generate Base64"}
            </button>
          )}
        </div>
      </nav>

      {/* 2. Workspace Area */}
      <main className="max-w-screen-xl mx-auto p-8 space-y-20">
        {!image ? (
          <div className="h-[70vh] flex flex-col items-center justify-center border-2 border-dashed border-zinc-800 rounded-[3rem] bg-zinc-900/30">
            <div className="w-20 h-20 bg-zinc-800 rounded-full flex items-center justify-center text-3xl mb-6">📁</div>
            <h2 className="text-2xl font-bold mb-2">Editor is Empty</h2>
            <p className="text-zinc-500 max-w-xs text-center">Upload a high-resolution image to begin the multi-aspect framing process.</p>
          </div>
        ) : (
          <div className="space-y-32 pb-40">
            {RATIOS.map((ratio) => (
              <section key={ratio.text} className="group">
                {/* Section Header */}
                <div className="flex items-end justify-between mb-6 border-b border-zinc-800 pb-4">
                  <div>
                    <span className="text-indigo-500 text-xs font-black uppercase tracking-[0.2em]">Aspect Ratio</span>
                    <h3 className="text-3xl font-bold mt-1">{ratio.label}</h3>
                  </div>
                  <div className="text-right">
                    <p className="text-zinc-500 text-xs font-mono uppercase">Current Zoom</p>
                    <p className="text-2xl font-black">{Math.round((crops[ratio.text]?.zoom || 1) * 100)}%</p>
                  </div>
                </div>

                {/* BIG Editor Window */}
                <div className="relative w-full overflow-hidden rounded-[2rem] bg-zinc-900 shadow-2xl ring-1 ring-zinc-800 h-[600px]">
                  <Cropper
                    image={image}
                    crop={{ x: crops[ratio.text].x, y: crops[ratio.text].y }}
                    zoom={crops[ratio.text].zoom}
                    aspect={ratio.value}
                    onCropChange={(c) => setCrops(prev => ({ ...prev, [ratio.text]: { ...prev[ratio.text], ...c } }))}
                    onZoomChange={(z) => setCrops(prev => ({ ...prev, [ratio.text]: { ...prev[ratio.text], zoom: z } }))}
                    onCropComplete={(_, px) => setCompletedCrops(prev => ({ ...prev, [ratio.text]: px }))}
                    objectFit="cover"
                    showGrid={true}
                  />
                </div>

                {/* Floating Zoom Control (Large & Accessible) */}
                <div className="mt-8 flex items-center gap-8 bg-zinc-900/50 p-6 rounded-2xl border border-zinc-800">
                  <span className="text-xs font-bold text-zinc-500 uppercase tracking-widest min-w-[80px]">Adjust Zoom</span>
                  <input
                    type="range"
                    min={1}
                    max={3}
                    step={0.01}
                    value={crops[ratio.text].zoom}
                    onChange={(e) => setCrops(prev => ({ ...prev, [ratio.text]: { ...prev[ratio.text], zoom: Number(e.target.value) } }))}
                    className="flex-1 accent-indigo-500 h-2 bg-zinc-800 rounded-lg appearance-none cursor-pointer"
                  />
                  <button 
                    onClick={() => setCrops(prev => ({ ...prev, [ratio.text]: { x:0, y:0, zoom: 1 } }))}
                    className="text-[10px] font-black uppercase tracking-widest text-zinc-600 hover:text-white"
                  >
                    Reset
                  </button>
                </div>
              </section>
            ))}
          </div>
        )}
      </main>

      {/* 3. Global Results Modal/Area */}
      {Object.keys(results).length > 0 && (
        <div className="fixed inset-0 z-[100] bg-zinc-950 flex flex-col">
          <header className="p-8 border-b border-zinc-800 flex justify-between items-center">
            <h2 className="text-2xl font-black">EXPORT BUNDLE</h2>
            <button onClick={() => setResults({})} className="text-zinc-500 hover:text-white font-bold">Close Editor</button>
          </header>
          <div className="flex-1 overflow-y-auto p-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {Object.entries(results).map(([ratio, b64]) => (
              <div key={ratio} className="bg-zinc-900 rounded-3xl p-6 space-y-4 border border-zinc-800">
                <div className="flex justify-between items-center">
                  <span className="text-xs font-bold text-indigo-500 uppercase">{ratio} Result</span>
                  <button 
                    onClick={() => {navigator.clipboard.writeText(b64); alert('Copied!');}}
                    className="text-[10px] bg-indigo-600 px-3 py-1 rounded-full font-bold"
                  >
                    Copy Base64
                  </button>
                </div>
                <img src={b64} className="w-full rounded-xl border border-white/5 shadow-lg" alt="Crop preview" />
                <textarea 
                  readOnly 
                  value={b64} 
                  className="w-full h-24 bg-zinc-950 text-[10px] font-mono p-4 rounded-xl border-none outline-none text-zinc-600"
                />
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------------- CANVAS EXPORT UTILITY ---------------- */
async function getCroppedImg(imageSrc: string, pixelCrop: any): Promise<string> {
  const image = new Image();
  image.src = imageSrc;
  await new Promise((resolve) => (image.onload = resolve));

  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) return "";

  canvas.width = pixelCrop.width;
  canvas.height = pixelCrop.height;

  ctx.drawImage(
    image,
    pixelCrop.x,
    pixelCrop.y,
    pixelCrop.width,
    pixelCrop.height,
    0,
    0,
    pixelCrop.width,
    pixelCrop.height
  );

  return canvas.toDataURL("image/jpeg", 0.9);
}