'use client';
import React, { type SyntheticEvent } from 'react';
import ReactCrop, { type Crop, type PixelCrop } from 'react-image-crop';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogFooter,
  DialogTrigger,
  DialogTitle,
} from '@/components/ui/dialog';
import 'react-image-crop/dist/ReactCrop.css';
// import { FileWithPreview } from "@/app/demo/form/tooltip/page";
import { CropIcon } from 'lucide-react';
import CommonImage from '@/components/common/CommonImage';
export type FileWithPreview = FileWithPath & {
  preview: string;
};
import { FileWithPath } from 'react-dropzone';
interface ImageCropperProps {
  dialogOpen: boolean;
  setDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
  selectedFile: FileWithPreview | null;
  setSelectedFile: React.Dispatch<React.SetStateAction<FileWithPreview | null>>;
}
export const ImageCropper: React.FC<ImageCropperProps> = ({
  dialogOpen,
  setDialogOpen,
  selectedFile,
  setSelectedFile,
}) => {
  const imgRef = React.useRef<HTMLImageElement | null>(null);
  const hasInitializedCrop = React.useRef(false);
  const [crop, setCrop] = React.useState<Crop | undefined>(undefined);
  const [croppedImageUrl, setCroppedImageUrl] = React.useState<string>('');
  const [croppedImage, setCroppedImage] = React.useState<string>('');
  const [cropTooSmall, setCropTooSmall] = React.useState<boolean>(false);
  const onImageLoad = (e: SyntheticEvent<HTMLImageElement>) => {
    if (hasInitializedCrop.current) return;
    const { width, height } = e.currentTarget;
    const initialSize = Math.min(width, height, 200); // ensure box fits
    setCrop({
      unit: 'px',
      x: 0, // left
      y: 0, // top
      width: initialSize,
      height: initialSize,
    });
    hasInitializedCrop.current = true;
  };
  React.useEffect(() => {
    if (selectedFile) {
      hasInitializedCrop.current = false;
    }
  }, [selectedFile]);
  const getCroppedImg = (image: HTMLImageElement, crop: PixelCrop): string => {
    const canvas = document.createElement('canvas');
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    canvas.width = crop.width * scaleX;
    canvas.height = crop.height * scaleY;
    const ctx = canvas.getContext('2d');
    if (ctx) {
      ctx.imageSmoothingEnabled = false;
      ctx.drawImage(
        image,
        crop.x * scaleX,
        crop.y * scaleY,
        crop.width * scaleX,
        crop.height * scaleY,
        0,
        0,
        crop.width * scaleX,
        crop.height * scaleY,
      );
    }
    return canvas.toDataURL('image/png', 1.0);
  };
  const onCropComplete = (crop: PixelCrop) => {
    const isTooSmall = crop.width < 60 || crop.height < 60;
    setCropTooSmall(isTooSmall);
    if (imgRef.current && !isTooSmall) {
      const croppedImageUrl = getCroppedImg(imgRef.current, crop);
      setCroppedImageUrl(croppedImageUrl);
    }
  };
  const onCrop = () => {
    try {
      setCroppedImage(croppedImageUrl);
      setDialogOpen(false);
    } catch {
      alert('Something went wrong!');
    }
  };
  return (
    <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
      <DialogTrigger>
        <Avatar className="cursor-pointer profile-user-img img-responsive">
          <AvatarImage
            src={croppedImage ? croppedImage : selectedFile?.preview}
            alt="Profile DP"
          />
        </Avatar>
      </DialogTrigger>
      <DialogContent className="p-0 gap-0 pb-4 modal-common-widget profile-pic-update-widget">
        <DialogTitle className="p-2 pb-6 mb-6 modal-header">
          Profile Pic Update
        </DialogTitle>
        <div className="mt-0 main-scroll-widget">
          <ReactCrop
            crop={crop}
            onChange={(newCrop) => {
              setCrop(newCrop);
              const isTooSmall =
                (newCrop.width ?? 0) < 60 || (newCrop.height ?? 0) < 60;
              setCropTooSmall(isTooSmall);
            }}
            onComplete={onCropComplete}
            minWidth={60}
            minHeight={60}
            className="w-full"
            keepSelection
          >
            <Avatar className="size-full rounded-none">
              <AvatarImage
                ref={imgRef}
                className="size-full rounded-none"
                alt="Image Cropper Shell"
                src={selectedFile?.preview}
                onLoad={onImageLoad}
              />
              <AvatarFallback className="size-full min-h-[460px] rounded-none">
                Loading...
              </AvatarFallback>
            </Avatar>
          </ReactCrop>
          {cropTooSmall && (
            <p className="text-sm text-red-500 mt-2 text-center">
              Crop size must be at least 60×60 pixels.
            </p>
          )}
        </div>
        <DialogFooter className="p-2 pt-0 justify-center modal-footer">
          <DialogClose asChild>
            <Button
              size="sm"
              type="reset"
              className="m-0 p-4 refresh-btn bg-transparent shadow primary-button-refresh"
              variant="outline"
              onClick={() => setSelectedFile(null)}
            >
              <CommonImage
                classname="icon icon-refresh"
                src="/main/refresh-icn.webp"
                width={15}
                height={15}
                alt="refresh"
              />
            </Button>
          </DialogClose>
          <Button
            type="submit"
            size="sm"
            className="m-0 primary-button pr-4 pl-"
            onClick={onCrop}
            disabled={cropTooSmall || !crop}
          >
            <CropIcon className="mr-1.5 size-2" />
            Crop
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
