"use client";

import { useState, useCallback } from "react";
import Cropper from "react-easy-crop";
import { ZoomIn, ZoomOut } from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { createCroppedImage } from "./cropImage";
import { getBaseFrameDimensions } from "./cropFrame";
import { useImagePreviewStyles } from "./useImagePreviewStyles";
import type { Area } from "react-easy-crop";

const MIN_ZOOM = 1;
const MAX_ZOOM = 3;
const ZOOM_STEP = 0.1;

interface CropModalProps {
  imageSrc: string;
  onCropComplete: (croppedImage: File) => void;
  onCancel: () => void;
  aspectRatio: number;
  cropShape: "rect" | "round";
  cropWidth?: number;
  cropHeight?: number;
  cropDisplayMode?: "opportunity" | "license" | "profile";
}

const CropModal: React.FC<CropModalProps> = ({
  imageSrc,
  onCropComplete,
  onCancel,
  aspectRatio,
  cropShape,
  cropWidth,
  cropHeight,
  cropDisplayMode,
}) => {
  // Set while the crop is being drawn, so a second Save cannot add the image twice.
  const [saving, setSaving] = useState(false);
  const handleCancel = (e?: React.MouseEvent) => {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    if (saving) return;
    onCancel();
  };

  const [crop, setCrop] = useState({ x: 0, y: 0 });
  const [zoom, setZoom] = useState(1);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(
    null
  );
  const { t } = useTranslation();

  useImagePreviewStyles();


  const baseFrame = getBaseFrameDimensions({
    cropDisplayMode,
    cropWidth,
    cropHeight,
    aspectRatio,
  });
  const cropperAspect = baseFrame.aspectRatio;

  /*
   * `Area` is `react-easy-crop`'s own exported type — the pixel rectangle its
   * `onCropComplete` hands back. The first argument, which these callbacks
   * ignore, is the same rectangle expressed in percentages.
   */
  const onCropCompleteCallback = useCallback(
    (_percentageArea: Area, pixelArea: Area) => {
      setCroppedAreaPixels(pixelArea);
    },
    []
  );

  const handleCropSave = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();

    if (saving || !croppedAreaPixels || !imageSrc) return;
    setSaving(true);
    try {
      const croppedImage = await createCroppedImage(
        imageSrc,
        croppedAreaPixels,
        "cropped-image.jpg"
      );
      onCropComplete(croppedImage);
    } catch {
      // A failed decode used to be an unhandled rejection: Save did nothing.
      toast.error(t("COMMON.CROP_FAILED"));
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={true}
      onClose={handleCancel}
      title={t("COMMON.CROP_IMAGE")}
      size="small"
      position="default"
      closeOnOutsideClick={false}
      showCloseButton={true}
    >
      {/* One line of help instead of three boxes (client, 2026-10-15). The
          old yellow box quoted a 1280×367 banner size, but every call site
          crops a square now (`cropFrame.ts`), so it described the wrong
          frame. */}
      <p className="mb-3 text-center text-sm text-secondary-102">
        {t("COMMON.CROP_HINT")}
      </p>

      <div className="relative mx-auto h-[300px] w-full overflow-hidden rounded-xl bg-[#1f1f23] sm:h-[340px]">
        <Cropper
          image={imageSrc}
          crop={crop}
          zoom={zoom}
          aspect={cropperAspect}
          cropShape={cropShape}
          onCropChange={setCrop}
          onCropComplete={onCropCompleteCallback}
          onZoomChange={setZoom}
          showGrid={true}
          objectFit="contain"
          style={{
            containerStyle: { width: "100%", height: "100%", position: "relative" },
            cropAreaStyle: {
              border: "2px solid #fff",
              boxShadow: "0 0 0 9999em rgba(0, 0, 0, 0.6)",
              color: "rgba(255, 255, 255, 0.6)",
            },
            mediaStyle: { maxHeight: "100%", maxWidth: "100%", objectFit: "contain" },
          }}
        />
      </div>

      <div className="mt-4 flex items-center gap-3">
        <button
          type="button"
          onClick={() => setZoom((z) => Math.max(MIN_ZOOM, +(z - ZOOM_STEP).toFixed(1)))}
          className="shrink-0 text-secondary-102 hover:text-primary-5"
          aria-label={t("COMMON.ZOOM_OUT")}
        >
          <ZoomOut className="h-5 w-5" aria-hidden="true" />
        </button>
        <input
          type="range"
          min={MIN_ZOOM}
          max={MAX_ZOOM}
          step={ZOOM_STEP}
          value={zoom}
          onChange={(e) => setZoom(Number(e.target.value))}
          aria-label={t("COMMON.ZOOM")}
          className="no-custom-background h-1.5 w-full cursor-pointer appearance-none rounded-full bg-gray-200 accent-primary-5"
        />
        <button
          type="button"
          onClick={() => setZoom((z) => Math.min(MAX_ZOOM, +(z + ZOOM_STEP).toFixed(1)))}
          className="shrink-0 text-secondary-102 hover:text-primary-5"
          aria-label={t("COMMON.ZOOM_IN")}
        >
          <ZoomIn className="h-5 w-5" aria-hidden="true" />
        </button>
      </div>

      <div className="mt-5 flex justify-end gap-3">
        <Button type="button" variant="secondary" size="medium" onClick={handleCancel}>
          {t("COMMON.CANCEL")}
        </Button>
        <Button type="button" variant="primary" size="medium" onClick={handleCropSave} loading={saving} disabled={saving || !croppedAreaPixels}>
          {t("COMMON.SAVE")}
        </Button>
      </div>
    </Modal>
  );
};

export default CropModal;
