import Cropper from "cropperjs";
import type { CropperCanvas, CropperImage, CropperSelection } from "cropperjs";
import httpClient from "../../../utils/http-client";
import Alpine from "alpinejs";

interface CropperResult {
    image: string;
    imageUrl: string;
}

type CropCallback = (result: CropperResult) => void;

interface Bounds {
    x: number;
    y: number;
    width: number;
    height: number;
}

/**
 * 初期選択範囲の画像に対する割合（v1 の autoCropArea 相当）
 */
const INITIAL_COVERAGE = 0.8;

/**
 * 小数誤差で選択範囲の判定が厳しくなりすぎないための許容値（px）
 */
const BOUNDS_TOLERANCE = 1;

/**
 * Cropper.js v2 のテンプレート
 * - 選択範囲外のドラッグで画像を移動（v1 の dragMode: "move" 相当）
 * - ホイールで画像を拡大縮小、回転・傾斜は無効
 * - 選択範囲は移動・リサイズ可能
 */
const buildCropperTemplate = (aspectRatio: number): string => {
    const aspectRatioAttribute = aspectRatio > 0 ? ` aspect-ratio="${aspectRatio}"` : "";
    const resizeHandles = ["n", "e", "s", "w", "ne", "nw", "se", "sw"]
        .map((direction) => `<cropper-handle action="${direction}-resize"></cropper-handle>`)
        .join("");

    return (
        '<cropper-canvas background style="width: 100%; height: 60vh;">' +
        '<cropper-image translatable scalable></cropper-image>' +
        "<cropper-shade></cropper-shade>" +
        '<cropper-handle action="move" plain></cropper-handle>' +
        `<cropper-selection initial-coverage="${INITIAL_COVERAGE}"${aspectRatioAttribute} movable resizable outlined>` +
        '<cropper-grid role="grid" bordered covered></cropper-grid>' +
        "<cropper-crosshair centered></cropper-crosshair>" +
        '<cropper-handle action="move" theme-color="rgba(255, 255, 255, 0)"></cropper-handle>' +
        resizeHandles +
        "</cropper-selection>" +
        "</cropper-canvas>"
    );
};

/**
 * 要素のキャンバス内での表示領域を取得
 */
const getBoundsInCanvas = (cropperCanvas: CropperCanvas, element: Element): Bounds => {
    const canvasRect = cropperCanvas.getBoundingClientRect();
    const elementRect = element.getBoundingClientRect();

    return {
        x: elementRect.left - canvasRect.left,
        y: elementRect.top - canvasRect.top,
        width: elementRect.width,
        height: elementRect.height,
    };
};

/**
 * 選択範囲が画像の表示領域内に収まっているか（v1 の viewMode: 1 相当）
 */
const isWithinBounds = (selection: Bounds, imageBounds: Bounds): boolean => {
    return (
        selection.x >= imageBounds.x - BOUNDS_TOLERANCE &&
        selection.y >= imageBounds.y - BOUNDS_TOLERANCE &&
        selection.x + selection.width <= imageBounds.x + imageBounds.width + BOUNDS_TOLERANCE &&
        selection.y + selection.height <= imageBounds.y + imageBounds.height + BOUNDS_TOLERANCE
    );
};

/**
 * 変換行列適用後の画像の表示領域を算出（回転・傾斜は無効のため拡大率と移動量のみ考慮）
 * 画像は中心を基準に変換されるため、変換前の中心位置から逆算する
 */
const getTransformedBounds = (currentBounds: Bounds, oldMatrix: number[], newMatrix: number[]): Bounds => {
    const [oldScaleX, , , oldScaleY, oldTranslateX, oldTranslateY] = oldMatrix;
    const [newScaleX, , , newScaleY, newTranslateX, newTranslateY] = newMatrix;
    const naturalWidth = currentBounds.width / oldScaleX;
    const naturalHeight = currentBounds.height / oldScaleY;
    const originX = currentBounds.x + currentBounds.width / 2 - oldTranslateX;
    const originY = currentBounds.y + currentBounds.height / 2 - oldTranslateY;
    const width = naturalWidth * newScaleX;
    const height = naturalHeight * newScaleY;

    return {
        x: originX + newTranslateX - width / 2,
        y: originY + newTranslateY - height / 2,
        width,
        height,
    };
};

/**
 * 選択範囲を画像の表示領域内に制限する
 */
const restrictSelectionToImage = (
    cropperCanvas: CropperCanvas,
    cropperImage: CropperImage,
    cropperSelection: CropperSelection
): void => {
    cropperSelection.addEventListener("change", (event) => {
        const detail = (event as CustomEvent<Bounds>).detail;
        if (!isWithinBounds(detail, getBoundsInCanvas(cropperCanvas, cropperImage))) {
            event.preventDefault();
        }
    });

    cropperImage.addEventListener("transform", (event) => {
        const { matrix, oldMatrix } = (event as CustomEvent<{ matrix: number[]; oldMatrix: number[] }>).detail;
        const transformedBounds = getTransformedBounds(
            getBoundsInCanvas(cropperCanvas, cropperImage),
            oldMatrix,
            matrix
        );

        if (!isWithinBounds(cropperSelection, transformedBounds)) {
            event.preventDefault();
        }
    });
};

/**
 * 選択範囲を画像の中央に初期配置する
 */
const fitSelectionToImage = (
    cropperCanvas: CropperCanvas,
    cropperImage: CropperImage,
    cropperSelection: CropperSelection,
    aspectRatio: number
): void => {
    const imageBounds = getBoundsInCanvas(cropperCanvas, cropperImage);
    let width = imageBounds.width * INITIAL_COVERAGE;
    let height = imageBounds.height * INITIAL_COVERAGE;

    if (aspectRatio > 0) {
        if (width / height > aspectRatio) {
            width = height * aspectRatio;
        } else {
            height = width / aspectRatio;
        }
    }

    cropperSelection.$change(
        imageBounds.x + (imageBounds.width - width) / 2,
        imageBounds.y + (imageBounds.height - height) / 2,
        width,
        height
    );
};

Alpine.data("imageCropper", () => ({
    isOpen: false,
    isCropping: false,
    cropper: null as Cropper | null,
    aspectRatio: NaN,
    callback: null as CropCallback | null,

    /**
     * クロッパーモーダルを開く
     */
    openCropper(
        imageUrl: string,
        aspectRatio: number,
        callback: CropCallback
    ): void {
        this.aspectRatio = aspectRatio && aspectRatio > 0 ? aspectRatio : NaN;
        this.callback = callback;
        this.isOpen = true;

        this.$nextTick(() => {
            const imgEl = this.$refs.cropperImage as HTMLImageElement;
            if (!imgEl) {
                return;
            }

            // 画像読み込み後にCropper.jsを初期化（srcより先にonloadを設定）
            imgEl.onload = () => {
                this.destroyCropper();
                this.initCropper(imgEl);
            };

            // 同じURLでもloadイベントを発火させるため一度srcをリセット
            imgEl.src = "";
            imgEl.src = imageUrl;
        });
    },

    /**
     * Cropper.js v2 を初期化
     */
    initCropper(imgEl: HTMLImageElement): void {
        const cropper = new Cropper(imgEl, {
            template: buildCropperTemplate(this.aspectRatio),
        });
        this.cropper = cropper;

        const cropperCanvas = cropper.getCropperCanvas();
        const cropperImage = cropper.getCropperImage();
        const cropperSelection = cropper.getCropperSelection();
        if (!cropperCanvas || !cropperImage || !cropperSelection) {
            return;
        }

        cropperImage.$ready().then(() => {
            requestAnimationFrame(() => {
                fitSelectionToImage(cropperCanvas, cropperImage, cropperSelection, this.aspectRatio);
                restrictSelectionToImage(cropperCanvas, cropperImage, cropperSelection);
            });
        });
    },

    /**
     * トリミングを確定してアップロード
     */
    async confirmCrop(): Promise<void> {
        if (!this.cropper || !this.callback) {
            return;
        }

        const cropperImage = this.cropper.getCropperImage();
        const cropperSelection = this.cropper.getCropperSelection();
        if (!cropperImage || !cropperSelection) {
            return;
        }

        this.isCropping = true;

        try {
            // 表示倍率を打ち消し、元画像の解像度で切り出す
            const [displayScale] = cropperImage.$getTransform();
            const canvas = await cropperSelection.$toCanvas({
                width: Math.round(cropperSelection.width / displayScale),
                beforeDraw: (context) => {
                    context.imageSmoothingEnabled = true;
                    context.imageSmoothingQuality = "high";
                },
            });

            const blob = await new Promise<Blob | null>((resolve) => {
                canvas.toBlob(
                    (b: Blob | null) => resolve(b),
                    "image/png",
                    1.0
                );
            });

            if (!blob) {
                throw new Error("トリミング画像の生成に失敗しました");
            }

            // FormDataの作成
            const formData = new FormData();
            formData.append("image", blob, "cropped.png");

            // CSRFトークンを取得
            const csrfToken =
                document
                    .querySelector('meta[name="csrf-token"]')
                    ?.getAttribute("content") || "";

            // 一時アップロードAPIに送信
            const response = await httpClient.post(
                "/user_admin/upload-temp-image",
                formData,
                {
                    headers: {
                        "X-CSRF-TOKEN": csrfToken,
                        "Content-Type": "multipart/form-data",
                    },
                }
            );

            if (!response.data || !response.data.filename) {
                throw new Error("サーバーからの応答が不正です");
            }

            const result: CropperResult = {
                image: response.data.filename,
                imageUrl: `/user_admin/access-temp-attachment/${response.data.filename}`,
            };

            this.callback(result);
            this.closeCropper();
        } catch (error) {
            console.error("トリミングに失敗しました:", error);
            alert("トリミングに失敗しました");
        } finally {
            this.isCropping = false;
        }
    },

    /**
     * クロッパーモーダルを閉じる
     */
    closeCropper(): void {
        this.destroyCropper();
        this.isOpen = false;
        this.callback = null;
    },

    /**
     * Cropperインスタンスを破棄
     */
    destroyCropper(): void {
        if (this.cropper) {
            this.cropper.destroy();
            this.cropper = null;
        }
    },
}));
