import { ArrowLeftCircle, ArrowRightCircle, ArrowRightFromLineIcon, Trash } from "lucide-react";
import Image from "next/image";
import { useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";
import { Button } from "./ui/button";

interface DropzoneProps {
  onChange: (base64Array: { url: string; order: number }[]) => void;
  onRemove: (index: number) => void;
  label: string;
  value: { url: string; order: number }[];
  disabled?: boolean;
  field: {
    value: { url: string; order: number }[];
    onChange: (value: { url: string; order: number }[]) => void;
  };
  maxFiles: number;
}

const ImageUpload: React.FC<DropzoneProps> = ({ onChange, onRemove, label, value, disabled, field, maxFiles }) => {
  const [base64Array, setBase64Array] = useState<{ url: string; order: number }[]>(value);

  const handleChange = useCallback((newBase64Array: string[]) => {
    const newImages = newBase64Array.map((url, index) => ({ url, order: index + base64Array.length }));
    const updatedArray = [...base64Array, ...newImages];
    updatedArray.sort((a, b) => a.order - b.order);
    setBase64Array(updatedArray);
    onChange(updatedArray);
  }, [base64Array, onChange]);


  const handleReorder = useCallback((startIndex: number, endIndex: number) => {
    const reorderedArray = arrayMove(base64Array, startIndex, endIndex);
    setBase64Array(reorderedArray);
    const reorderedValue = arrayMove(field.value, startIndex, endIndex);
    field.onChange(reorderedValue);
  }, [base64Array, field]);

  const arrayMove = (array: any[], from: number, to: number) => {
    const newArray = [...array];
    const [removed] = newArray.splice(from, 1);
    newArray.splice(to, 0, removed);
    newArray.forEach((item, index) => {
      item.order = index;
    });
    
    return newArray;
  };
  

  const handleDrop = useCallback((files: File[]) => {
    const newBase64Array: string[] = [];
    files.forEach((file) => {
      const reader = new FileReader();
      reader.onload = (event: ProgressEvent<FileReader>) => {
        const base64 = event.target?.result as string;
        newBase64Array.push(base64);
        if (newBase64Array.length === files.length) {
          handleChange(newBase64Array);
        }
      };
      reader.readAsDataURL(file);
    });
  }, [handleChange]);

  const handleRemove = useCallback((index: number) => {
    const updatedArray = [...base64Array];
    updatedArray.splice(index, 1);
    setBase64Array(updatedArray);
    const fieldValue = field.value.filter((_, i) => i !== index);
    field.onChange(fieldValue);
  }, [base64Array, field]);

  const { getRootProps, getInputProps } = useDropzone({
    maxFiles: maxFiles,
    onDrop: handleDrop,
    disabled,
    accept: {
      'image/jpeg': [],
      'image/png': [],
      'image/webp': [],
    }
  });

  return (
    <div>
      <div className="mb-4 flex items-center gap-4">
        {base64Array.map((base64, index) => (
          <div key={index} className="relative w-[200px] h-[200px] rounded-md overflow-hidden">
            <div className="z-10 absolute top-2 right-2">
              <Button type="button" onClick={() => handleRemove(index)} variant="destructive" size="icon">
                <Trash className="h-4 w-4" />
              </Button>

            </div>
            {(base64Array.length > 1 && maxFiles > 1) &&
              <div className="flex flex-row z-10 absolute w-[100%] bottom-2 justify-center space-x-3">
                <Button type="button" onClick={() => handleReorder(index, index - 1)} disabled={index === 0}>
                  <ArrowLeftCircle className="h-5 w-5" />
                </Button>
                <Button type="button" onClick={() => handleReorder(index, index + 1)} disabled={index === base64Array.length - 1}>
                  <ArrowRightCircle className="h-5 w-5" />
                </Button>
              </div>
            }
            <Image
              fill
              className="object-cover"
              alt="Image"
              src={base64.url}
            />
          </div>
        ))}
      </div>

      <div {...getRootProps({ className: 'w-60 p-4 text-white text-center border-2 border-dotted rounded-md border-neutral-700' })}>
        <input {...getInputProps()} />
        {base64Array.length === 0 ? (
          <p className="text-white">{label}</p>
        ) : <p className="text-white">{label}</p>}
      </div>
    </div>
  );
}

export default ImageUpload;