import { useRef } from 'react';
import IconTrash from './Icon/IconTrash';
import IconUpload from './Icon/IconUpload';

type Props = {
  label: string;
  hint?: string;
  value: string | null;
  onChange: (url: string | null, file?: File | null) => void;

  shape?: 'circle' | 'square';
  size?: number;
};

const ImageUpload = ({
  label,
  hint,
  value,
  onChange,
  shape = 'square',
  size = 80,
}: Props) => {
  const inputRef = useRef<HTMLInputElement>(null);

  const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      onChange(URL.createObjectURL(file), file);
    }
  };

  const handleRemove = () => {
    onChange(null, null);

    // reset file input so same file can be re-uploaded
    if (inputRef.current) {
      inputRef.current.value = '';
    }
  };

  return (
    <div>
      <label className="mb-1 block text-sm font-medium text-gray-800">
        {label}
      </label>

      <div className="flex items-center gap-4">
        {/* Preview Box */}
        <div
          onClick={() => inputRef.current?.click()}
          style={{ width: size, height: size }}
          className={`cursor-pointer overflow-hidden border-2 border-gray-200 shadow-sm transition hover:border-amber-400 ${
            shape === 'circle' ? 'rounded-full' : 'rounded-lg'
          }`}
        >
          {value ? (
            <img
              src={value}
              className="h-full w-full object-cover"
              alt={label}
            />
          ) : (
            <div className="flex h-full w-full items-center justify-center bg-gray-100 text-gray-400 text-xs">
              Upload
            </div>
          )}
        </div>

        {/* Buttons */}
        <div className="flex flex-col gap-1">
          {hint && <p className="text-xs text-gray-500">{hint}</p>}

          <div className="flex gap-2">
            {/* Upload */}
            <button
              type="button"
              onClick={() => inputRef.current?.click()}
              className="rounded bg-white px-3 py-1 text-xs font-medium text-amber-600 shadow-sm ring-1 ring-amber-200 hover:bg-amber-50 transition"
            >
              <IconUpload/>
            </button>

            {/* Remove */}
            {value && (
              <button
                type="button"
                onClick={handleRemove}
                className="rounded bg-red-50 px-3 py-1 text-xs font-medium text-red-600 ring-1 ring-red-200 hover:bg-red-100 transition"
              >
                <IconTrash/>
              </button>
            )}
          </div>
        </div>

        {/* Hidden Input */}
        <input
          ref={inputRef}
          type="file"
          accept="image/*"
          className="hidden"
          onChange={handleFile}
        />
      </div>
    </div>
  );
};

export default ImageUpload;