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

interface ImageUploadFieldProps {
  label?: string;
  value: string;
  uploading?: boolean;
  onUpload: (file: File) => void;
  size?: number;
}

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

  const imgSrc = value
    ? config.baseUrl.replace(/\/+$/, "") +
      "/" +
      value.replace(/^\/+/, "")
    : "";

  return (
    <Box sx={{ display: "flex", flexDirection: "column", gap: 1, mb: 3 }}>
      <Typography variant="caption" color="text.secondary">{label}</Typography>
      <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
        <Avatar
          src={imgSrc}
          sx={{ width: size, height: size, borderRadius: 2 }}
        />

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