import CloudUploadOutlined from "@mui/icons-material/CloudUploadOutlined";
import Alert from "@mui/material/Alert";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { useRef, useState } from "react";
import { uploadExternalImage } from "../api/business.js";
import { useExternalI18n } from "../i18n/ExternalI18nProvider.jsx";
import { translateExternalError } from "../i18n/errors.js";

export function ExternalImageUploadField({ disabled, label, onChange, value }) {
  const { t } = useExternalI18n();
  const inputRef = useRef(null);
  const [error, setError] = useState("");
  const [uploading, setUploading] = useState(false);

  const handleFile = async (event) => {
    const file = event.target.files?.[0];
    event.target.value = "";
    if (!file) {
      return;
    }
    if (!file.type.startsWith("image/")) {
      setError(t("upload.imageOnly"));
      return;
    }
    if (file.size > 10 * 1024 * 1024) {
      setError(t("upload.sizeLimit"));
      return;
    }

    setError("");
    setUploading(true);
    try {
      const url = await uploadExternalImage(file);
      if (!url) {
        const missingUrlError = new Error("missing upload URL");
        missingUrlError.translationKey = "upload.missingUrl";
        throw missingUrlError;
      }
      onChange(url);
    } catch (uploadError) {
      setError(translateExternalError(uploadError, t, "upload.failed"));
    } finally {
      setUploading(false);
    }
  };

  return (
    <Stack spacing={1}>
      <Typography color="text.secondary" variant="body2">{label}</Typography>
      <Box className="external-image-field">
        {value ? <img alt={t("upload.preview", { label })} src={value} /> : <Box className="external-image-placeholder">{t("upload.empty")}</Box>}
        <Button
          disabled={disabled || uploading}
          onClick={() => inputRef.current?.click()}
          startIcon={uploading ? <CircularProgress size={16} /> : <CloudUploadOutlined />}
          variant="outlined"
        >
          {uploading ? t("upload.uploading") : value ? t("upload.replace") : t("upload.select")}
        </Button>
        <input accept="image/*" hidden ref={inputRef} type="file" onChange={handleFile} />
      </Box>
      {error ? <Alert severity="error">{error}</Alert> : null}
    </Stack>
  );
}
