"use client";
import { useState, useCallback } from "react";
import Cropper, { Area } from "react-easy-crop";
import { getCroppedImg } from "@/utlis/cropImage";
import {
  Button,
  Modal,
  ModalBody,
  ModalContent,
  ModalHeader,
  ModalFooter,
} from "@heroui/react";

type ModalCropperProps = {
  open: boolean;
  image: string;
  aspect?: number;
  onCancel: () => void;
  onConfirm: (croppedBlob: Blob) => void | Promise<void>;
  /** Skip cropping and upload the file as selected (optional). */
  onUseOriginal?: () => void | Promise<void>;
  /** Label for the skip-crop button (e.g. next-intl). */
  useOriginalLabel?: string;
};

export default function ModalCropper({
  open,
  image,
  aspect = 1,
  onCancel,
  onConfirm,
  onUseOriginal,
  useOriginalLabel = "Use original image",
}: ModalCropperProps) {
  const [crop, setCrop] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
  const [zoom, setZoom] = useState<number>(1);
  const [rotation, setRotation] = useState<number>(0);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);
  const [pendingAction, setPendingAction] = useState<
    null | "confirm" | "original"
  >(null);
  const isBusy = pendingAction !== null;

  const onCropComplete = useCallback((_: Area, croppedAreaPixels: Area) => {
    setCroppedAreaPixels(croppedAreaPixels);
  }, []);

  const handleConfirm = async () => {
    if (isBusy || !croppedAreaPixels) return;
    try {
      setPendingAction("confirm");
      const croppedImageBlob = await getCroppedImg(
        image,
        croppedAreaPixels,
        rotation,
      );
      await onConfirm(croppedImageBlob);
    } finally {
      setPendingAction(null);
    }
  };

  const resetTransforms = () => {
    setZoom(1);
    setRotation(0);
    setCrop({ x: 0, y: 0 });
  };

  const handleUseOriginal = async () => {
    if (!onUseOriginal || isBusy) return;
    try {
      setPendingAction("original");
      await onUseOriginal();
    } finally {
      setPendingAction(null);
    }
  };

  return (
    <Modal
      isOpen={open}
      onOpenChange={() => {
        if (isBusy) return;
        onCancel();
      }}
      size="2xl"
      classNames={{
        base: "rounded-2xl",
        header: "border-b border-slate-100 pb-3",
        footer: "border-t border-slate-100 pt-3",
      }}
    >
      <ModalContent>
        <ModalHeader className="flex items-center gap-2.5">
          <div className="w-8 h-8 rounded-lg bg-primary/10 flex items-center justify-center">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="w-4 h-4 text-primary"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            >
              <path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z" />
              <line x1="3" y1="6" x2="21" y2="6" />
              <path d="M16 10a4 4 0 01-8 0" />
            </svg>
          </div>
          <span className="text-base font-bold text-slate-800">
            تعديل الصورة
          </span>
        </ModalHeader>

        <ModalBody className="px-4 py-4">
          {/* Crop area */}
          <div className="relative w-full h-[340px] sm:h-[400px] rounded-xl overflow-hidden bg-slate-900">
            <Cropper
              image={image}
              crop={crop}
              zoom={zoom}
              rotation={rotation}
              aspect={aspect}
              onCropChange={setCrop}
              onZoomChange={setZoom}
              onCropComplete={onCropComplete}
              cropShape="rect"
              showGrid={true}
              classes={{
                containerClassName: "rounded-xl",
                cropAreaClassName: "!border-2 !border-white/70 !rounded-lg",
              }}
            />
          </div>

          {/* Controls */}
          <div className="mt-4 space-y-3">
            {/* Zoom */}
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-1.5 w-20 shrink-0">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="w-4 h-4 text-slate-500"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <circle cx="11" cy="11" r="8" />
                  <line x1="21" y1="21" x2="16.65" y2="16.65" />
                  <line x1="11" y1="8" x2="11" y2="14" />
                  <line x1="8" y1="11" x2="14" y2="11" />
                </svg>
                <span className="text-xs font-medium text-slate-600">تكبير</span>
              </div>
              <input
                type="range"
                min={1}
                max={3}
                step={0.05}
                value={zoom}
                onChange={(e) => setZoom(Number(e.target.value))}
                disabled={isBusy}
                className="flex-1 h-1.5 rounded-full appearance-none bg-slate-200 accent-primary cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-webkit-slider-thumb]:shadow-md [&::-webkit-slider-thumb]:cursor-pointer"
              />
              <span className="text-xs text-slate-500 w-10 text-center tabular-nums">
                {Math.round(zoom * 100)}%
              </span>
            </div>

            {/* Rotation */}
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-1.5 w-20 shrink-0">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="w-4 h-4 text-slate-500"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M21.5 2v6h-6" />
                  <path d="M21.34 15.57a10 10 0 11-.57-8.38" />
                </svg>
                <span className="text-xs font-medium text-slate-600">تدوير</span>
              </div>
              <input
                type="range"
                min={0}
                max={360}
                step={1}
                value={rotation}
                onChange={(e) => setRotation(Number(e.target.value))}
                disabled={isBusy}
                className="flex-1 h-1.5 rounded-full appearance-none bg-slate-200 accent-primary cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-webkit-slider-thumb]:shadow-md [&::-webkit-slider-thumb]:cursor-pointer"
              />
              <span className="text-xs text-slate-500 w-10 text-center tabular-nums">
                {rotation}°
              </span>
            </div>

            {/* Quick actions */}
            <div className="flex items-center gap-2 pt-1">
              <button
                type="button"
                onClick={() => setRotation((r) => (r + 90) % 360)}
                disabled={isBusy}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 hover:border-slate-300 bg-white hover:bg-slate-50 text-xs font-medium text-slate-600 transition-all disabled:opacity-50"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="w-3.5 h-3.5"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d="M21.5 2v6h-6" />
                  <path d="M21.34 15.57a10 10 0 11-.57-8.38" />
                </svg>
                90°
              </button>
              <button
                type="button"
                onClick={resetTransforms}
                disabled={isBusy}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-slate-200 hover:border-slate-300 bg-white hover:bg-slate-50 text-xs font-medium text-slate-600 transition-all disabled:opacity-50"
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  className="w-3.5 h-3.5"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <polyline points="1 4 1 10 7 10" />
                  <polyline points="23 20 23 14 17 14" />
                  <path d="M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15" />
                </svg>
                إعادة ضبط
              </button>
            </div>
          </div>
        </ModalBody>

        <ModalFooter className="flex flex-wrap gap-2 justify-end">
          <Button
            variant="flat"
            onPress={onCancel}
            isDisabled={isBusy}
            className="rounded-xl font-medium"
          >
            إلغاء
          </Button>
          {onUseOriginal ? (
            <Button
              variant="bordered"
              onPress={() => void handleUseOriginal()}
              isLoading={pendingAction === "original"}
              isDisabled={isBusy}
              className="rounded-xl font-medium border-primary text-primary"
            >
              {useOriginalLabel}
            </Button>
          ) : null}
          <Button
            color="primary"
            onPress={() => void handleConfirm()}
            isLoading={pendingAction === "confirm"}
            isDisabled={isBusy || !croppedAreaPixels}
            className="rounded-xl font-medium shadow-sm"
          >
            تأكيد وحفظ
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
}
