import { useState, useRef, useEffect } from "react";
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import clsx from "clsx";

interface Props {
  imageUrl: string;
  selectedPlatforms: string[];
  onSave: (croppedBlob: Blob, croppedUrl: string) => void;
  onCancel: () => void;
}

interface AspectPreset {
  label: string;
  ratio: number;
  icon?: string;
}

// Platform-specific crop presets matching Viraly SPA Pintura config
const PLATFORM_PRESETS: Record<string, AspectPreset[]> = {
  Facebook: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Portrait 4:5", ratio: 4 / 5 },
    { label: "Landscape 1.91:1", ratio: 1.91 },
    { label: "Story 9:16", ratio: 9 / 16 },
  ],
  Instagram: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Portrait 3:4", ratio: 3 / 4 },
    { label: "Portrait 4:5", ratio: 4 / 5 },
    { label: "Landscape 1.91:1", ratio: 1.91 },
    { label: "Landscape 16:9", ratio: 16 / 9 },
    { label: "Story 9:16", ratio: 9 / 16 },
  ],
  Twitter: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Landscape 16:9", ratio: 16 / 9 },
    { label: "Portrait 9:16", ratio: 9 / 16 },
  ],
  LinkedIn: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Portrait 4:5", ratio: 4 / 5 },
    { label: "Landscape 1.91:1", ratio: 1.91 },
    { label: "Video 16:9", ratio: 16 / 9 },
  ],
  Pinterest: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Portrait 2:3", ratio: 2 / 3 },
    { label: "Portrait 4:5", ratio: 4 / 5 },
    { label: "Video 9:16", ratio: 9 / 16 },
  ],
  TikTok: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Portrait 2:3", ratio: 2 / 3 },
    { label: "Portrait 9:16", ratio: 9 / 16 },
    { label: "Landscape 16:9", ratio: 16 / 9 },
  ],
  YouTube: [
    { label: "Short 9:16", ratio: 9 / 16 },
    { label: "Video 16:9", ratio: 16 / 9 },
  ],
  Threads: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Portrait 4:5", ratio: 4 / 5 },
    { label: "Landscape 1.91:1", ratio: 1.91 },
    { label: "Video 9:16", ratio: 9 / 16 },
  ],
  Bluesky: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Portrait 4:5", ratio: 4 / 5 },
    { label: "Landscape 16:9", ratio: 16 / 9 },
    { label: "Portrait 9:16", ratio: 9 / 16 },
  ],
  Mastodon: [
    { label: "Square 1:1", ratio: 1 },
    { label: "Portrait 4:5", ratio: 4 / 5 },
    { label: "Landscape 16:9", ratio: 16 / 9 },
    { label: "Portrait 9:16", ratio: 9 / 16 },
  ],
};

// Default presets if no platform matched
const DEFAULT_PRESETS: AspectPreset[] = [
  { label: "Free", ratio: NaN },
  { label: "1:1", ratio: 1 },
  { label: "4:5", ratio: 4 / 5 },
  { label: "16:9", ratio: 16 / 9 },
  { label: "9:16", ratio: 9 / 16 },
];

export default function ImageEditor({ imageUrl, selectedPlatforms, onSave, onCancel }: Props) {
  const imageRef = useRef<HTMLImageElement>(null);
  const cropperRef = useRef<Cropper | null>(null);
  const [activeRatio, setActiveRatio] = useState<number>(NaN);
  const [rotation, setRotation] = useState(0);
  const [saving, setSaving] = useState(false);

  // Merge presets from all selected platforms (deduped)
  const presets = (() => {
    const seen = new Map<string, AspectPreset>();
    seen.set("Free", { label: "Free", ratio: NaN });
    for (const platform of selectedPlatforms) {
      const platformPresets = PLATFORM_PRESETS[platform];
      if (platformPresets) {
        for (const p of platformPresets) {
          if (!seen.has(p.label)) seen.set(p.label, p);
        }
      }
    }
    return seen.size > 1 ? [...seen.values()] : DEFAULT_PRESETS;
  })();

  useEffect(() => {
    const img = imageRef.current;
    if (!img) return;

    const initCropper = () => {
      // Destroy previous instance if exists
      if (cropperRef.current) {
        cropperRef.current.destroy();
        cropperRef.current = null;
      }

      cropperRef.current = new Cropper(img, {
        viewMode: 1,
        dragMode: "move",
        autoCropArea: 0.9,
        responsive: true,
        background: true,
        guides: true,
        checkCrossOrigin: false,
        checkOrientation: false,
        modal: true,
        highlight: true,
        cropBoxMovable: true,
        cropBoxResizable: true,
        toggleDragModeOnDblclick: true,
      });
    };

    // Wait for image to load if not already
    if (img.complete && img.naturalWidth > 0) {
      initCropper();
    } else {
      img.onload = initCropper;
    }

    return () => {
      cropperRef.current?.destroy();
      cropperRef.current = null;
    };
  }, [imageUrl]);

  const setAspectRatio = (ratio: number) => {
    setActiveRatio(ratio);
    cropperRef.current?.setAspectRatio(isNaN(ratio) ? NaN : ratio);
  };

  const rotate = (deg: number) => {
    setRotation((r) => r + deg);
    cropperRef.current?.rotate(deg);
  };

  const flipH = () => {
    const data = cropperRef.current?.getData();
    if (data) cropperRef.current?.scaleX(data.scaleX === -1 ? 1 : -1);
  };

  const flipV = () => {
    const data = cropperRef.current?.getData();
    if (data) cropperRef.current?.scaleY(data.scaleY === -1 ? 1 : -1);
  };

  const handleSave = () => {
    const canvas = cropperRef.current?.getCroppedCanvas({
      maxWidth: 4096,
      maxHeight: 4096,
      imageSmoothingEnabled: true,
      imageSmoothingQuality: "high",
    });
    if (!canvas) return;

    setSaving(true);
    canvas.toBlob(
      (blob) => {
        if (blob) {
          const url = URL.createObjectURL(blob);
          onSave(blob, url);
        }
        setSaving(false);
      },
      "image/jpeg",
      0.92
    );
  };

  return (
    <div className="vr-fixed vr-inset-0 vr-z-50 vr-flex vr-items-center vr-justify-center vr-bg-black/60" onClick={onCancel}>
      <div
        className="vr-bg-white vr-rounded-xl vr-shadow-2xl vr-w-full vr-max-w-2xl vr-mx-4 vr-overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="vr-flex vr-items-center vr-justify-between vr-px-5 vr-py-3 vr-border-b vr-border-gray-200">
          <h3 className="vr-text-sm vr-font-bold vr-text-gray-900">Edit Image</h3>
          <button onClick={onCancel} className="vr-text-gray-400 hover:vr-text-gray-600 vr-border-0 vr-bg-transparent vr-cursor-pointer vr-p-1">
            <i className="fa-solid fa-xmark" />
          </button>
        </div>

        {/* Cropper area */}
        <div style={{ maxHeight: "400px", overflow: "hidden", background: "#f0f0f0" }}>
          <img
            ref={imageRef}
            src={imageUrl}
            alt="Edit"
            style={{ display: "block", maxWidth: "100%" }}
          />
        </div>

        {/* Aspect ratio presets */}
        <div className="vr-px-4 vr-py-3 vr-border-t vr-border-gray-100">
          <div className="vr-flex vr-items-center vr-gap-1.5 vr-overflow-x-auto vr-pb-1">
            <span className="vr-text-xs vr-text-gray-400 vr-flex-shrink-0 vr-mr-1">Crop:</span>
            {presets.map((p) => (
              <button
                key={p.label}
                onClick={() => setAspectRatio(p.ratio)}
                className={clsx(
                  "vr-px-2.5 vr-py-1 vr-rounded-md vr-text-xs vr-font-medium vr-border-0 vr-cursor-pointer vr-whitespace-nowrap vr-transition-colors",
                  (isNaN(activeRatio) && isNaN(p.ratio)) || activeRatio === p.ratio
                    ? "vr-bg-primary-600 vr-text-white"
                    : "vr-bg-gray-100 vr-text-gray-600 hover:vr-bg-gray-200"
                )}
              >
                {p.label}
              </button>
            ))}
          </div>
        </div>

        {/* Tools + actions */}
        <div className="vr-flex vr-items-center vr-justify-between vr-px-4 vr-py-3 vr-border-t vr-border-gray-100">
          {/* Rotate & flip */}
          <div className="vr-flex vr-gap-1">
            <button onClick={() => rotate(-90)} className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-md vr-bg-gray-100 vr-text-gray-600 hover:vr-bg-gray-200 vr-border-0 vr-cursor-pointer" title="Rotate left">
              <i className="fa-solid fa-rotate-left" style={{ fontSize: "13px" }} />
            </button>
            <button onClick={() => rotate(90)} className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-md vr-bg-gray-100 vr-text-gray-600 hover:vr-bg-gray-200 vr-border-0 vr-cursor-pointer" title="Rotate right">
              <i className="fa-solid fa-rotate-right" style={{ fontSize: "13px" }} />
            </button>
            <button onClick={flipH} className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-md vr-bg-gray-100 vr-text-gray-600 hover:vr-bg-gray-200 vr-border-0 vr-cursor-pointer" title="Flip horizontal">
              <i className="fa-solid fa-arrows-left-right" style={{ fontSize: "13px" }} />
            </button>
            <button onClick={flipV} className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-md vr-bg-gray-100 vr-text-gray-600 hover:vr-bg-gray-200 vr-border-0 vr-cursor-pointer" title="Flip vertical">
              <i className="fa-solid fa-arrows-up-down" style={{ fontSize: "13px" }} />
            </button>
          </div>

          {/* Save / Cancel */}
          <div className="vr-flex vr-gap-2">
            <button
              onClick={onCancel}
              className="vr-px-4 vr-py-2 vr-text-xs vr-font-medium vr-text-gray-500 hover:vr-text-gray-700 vr-border-0 vr-bg-transparent vr-cursor-pointer"
            >
              Cancel
            </button>
            <button
              onClick={handleSave}
              disabled={saving}
              className="vr-inline-flex vr-items-center vr-gap-1.5 vr-px-4 vr-py-2 vr-bg-primary-600 vr-text-white vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-primary-700 vr-transition-colors disabled:vr-opacity-50 vr-border-0 vr-cursor-pointer"
            >
              {saving ? "Saving..." : "Save Changes"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
