"use client";

import { useCallback, useEffect, useState } from "react";
import Cropper from "react-easy-crop";
import { useTranslation } from "react-i18next";

import { Modal } from "@/components/ui/Modal";
import { Button } from "@/components/ui/Button";
import { createCroppedImage } from "./createCroppedImage";
import type { Area } from "react-easy-crop";
interface ProfilePictureCropModalProps {
  imageSrc: string;
  onCropComplete: (croppedImage: File) => Promise<void> | void;
  onCancel: () => void;
}

export default function ProfilePictureCropModal({
  imageSrc,
  onCropComplete,
  onCancel,
}: ProfilePictureCropModalProps) {
  const [crop, setCrop] = useState({ x: 0, y: 0 });
  const [zoom, setZoom] = useState(1);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);
  // Save stays disabled until the upload settles: a second click re-uploaded.
  const [saving, setSaving] = useState(false);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const { t } = useTranslation();

  /*
   * `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);
    },
    []
  );

  /*
   * Render the live preview for the current rectangle. The work is async —
   * canvas plus `toBlob` — so the state write is a callback rather than a
   * synchronous effect body; it was reported by
   * `react-hooks/set-state-in-effect` only because it sat behind a
   * `useCallback` the rule followed into.
   *
   * `cancelled` is new and fixes a real race: dragging starts a render per
   * rectangle, and an earlier slower crop could resolve after a later one and
   * leave the wrong rectangle on screen. The zoom slider's own
   * `generatePreview()` call is gone for the same reason — it ran with the
   * *pre-zoom* rectangle; the cropper fires `onCropComplete` right after.
   */
  useEffect(() => {
    if (!croppedAreaPixels || !imageSrc) return;
    let cancelled = false;

    void (async () => {
      try {
        const croppedImage = await createCroppedImage(
          imageSrc,
          croppedAreaPixels,
          "preview.jpg",
        );
        if (cancelled) return;
        const created = URL.createObjectURL(croppedImage);
        setPreviewUrl((previous) => {
          if (previous) URL.revokeObjectURL(previous);
          return created;
        });
      } catch (error) {
        console.error("Failed to generate preview:", error);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [croppedAreaPixels, imageSrc]);

  // Release the last preview URL on unmount
  useEffect(
    () => () => {
      if (previewUrl) URL.revokeObjectURL(previewUrl);
    },
    [previewUrl],
  );

  const handleCropSave = async () => {
    if (saving || !croppedAreaPixels || !imageSrc) return;
    setSaving(true);
    try {
      const croppedImage = await createCroppedImage(imageSrc, croppedAreaPixels, "cropped-profile.jpg");
      await onCropComplete(croppedImage);
      if (previewUrl) URL.revokeObjectURL(previewUrl);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open
      onClose={onCancel}
      title={t("COMMON.CROP_IMAGE")}
      size="small"
      className="profile-picture-crop-dialog"
      position="default"
      style={{ padding: "12px" }}
      closeOnOutsideClick={false}
      showCloseButton
    >
      {/* Cropper */}
      <div className="profile-picture-crop-preview relative w-full overflow-hidden rounded-lg bg-gray-100">
        <Cropper
          image={imageSrc}
          crop={crop}
          zoom={zoom}
          aspect={1}
          cropShape="round"
          onCropChange={setCrop}
          onCropComplete={onCropCompleteCallback}
          onZoomChange={setZoom}
          showGrid
          objectFit="contain"
          style={{
            containerStyle: {
              width: "100%",
              height: "100%",
              backgroundColor: "#f3f4f6",
              position: "relative",
            },
            cropAreaStyle: {
              border: "2px solid #fff",
              boxShadow: "0 0 0 9999em rgba(0, 0, 0, 0.7)",
              color: "rgba(255, 255, 255, 0.7)",
            },
            mediaStyle: {
              maxHeight: "100%",
              maxWidth: "100%",
              objectFit: "contain",
            },
          }}
        />
      </div>

      <div className="mt-3 space-y-3">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            {t("COMMON.ZOOM")}
          </label>
          <input
            type="range"
            min={1}
            max={3}
            step={0.1}
            value={zoom}
            onChange={(e) => setZoom(Number(e.target.value))}
            className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer no-custom-background"
          />
        </div>

        <p className="rounded-lg bg-blue-50 px-2 py-2 text-center text-[11px] font-medium text-blue-700 sm:text-xs">
          {t("COMMON.PROFILE_CROP_HINT")}
        </p>
      </div>

      <div className="profile-picture-crop-actions mt-3 flex gap-3">
        <Button
          type="button"
          variant="secondary"
          size="medium"
          className="!w-auto min-w-0 flex-1"
          onClick={onCancel}
        >
          {t("COMMON.CANCEL")}
        </Button>
        <Button
          type="button"
          variant="primary"
          size="medium"
          className="!w-auto min-w-0 flex-1"
          onClick={handleCropSave}
          loading={saving}
        >
          {t("COMMON.SAVE")}
        </Button>
      </div>
    </Modal>
  );
}
