import * as React from "react";
import { Box, Button, Avatar, CircularProgress } from "@mui/material";
import { ImageUploadFieldProps } from "../types/props";

export default function ImageUploadField({
  label = "Upload Image",
  value,
  uploading = false,
  onUpload,
  size = 64,
}: ImageUploadFieldProps) {

  const imgSrc = value
    ? import.meta.env.VITE_API_BASE_URL.replace(/\/+$/, "") +
      "/" +
      value.replace(/^\/+/, "")
    : "";

  return (
    <Box sx={{ display: "flex", alignItems: "center", gap: 2, mb: 3 }}>
      <Avatar
        src={imgSrc}
        sx={{ width: size, height: size, borderRadius: 2 }}
      />

      <Button
        variant="outlined"
        component="label"
        disabled={uploading}
        startIcon={uploading && <CircularProgress size={16} />}
      >
        {uploading ? "Uploading..." : label}
        <input
          type="file"
          accept="image/*"
          hidden
          onChange={(e) => {
            const file = e.target.files?.[0];
            if (file) onUpload(file);
          }}
        />
      </Button>
    </Box>
  );
}
