import { useState, type CSSProperties } from "react";
import Image from "next/image";
import Button from "@/components/Button";

type ApiResponse = {
  imageUrl: string;
  alt?: string;
};

type RandomUnsplashProps = {
  compact?: boolean;
};

export default function RandomUnsplash({ compact = false }: RandomUnsplashProps) {
  const [loading, setLoading] = useState(false);
  const [image, setImage] = useState<ApiResponse | null>(null);
  const [error, setError] = useState<string | null>(null);

  const containerStyle: CSSProperties = {
    textAlign: compact ? "left" : "center",
    marginTop: compact ? 0 : 24,
    display: "flex",
    flexDirection: "column",
    gap: 10,
  };

  async function fetchRandomImage() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/unsplash/random");
      if (!res.ok) throw new Error(`Fehler: ${res.status}`);
      const data = await res.json();
      setImage(data);
    } catch (e) {
      setError("Bild konnte nicht geladen werden.");
      console.error(e);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={containerStyle}>
      <Button onClick={fetchRandomImage} style={compact ? { alignSelf: "flex-start" } : undefined}>
        {loading ? "Lade Bild..." : "Bild anzeigen"}
      </Button>

      {error && <p style={{ color: "crimson", marginTop: 12 }}>{error}</p>}

      {image && (
        <figure
          style={{
            position: "relative",
            width: "100%",
            aspectRatio: "16 / 9",
            overflow: "hidden",
            borderRadius: 12,
            marginTop: compact ? 12 : 20,
          }}
        >
          <Image
            src={image.imageUrl}
            alt={image.alt || "Random Unsplash"}
            fill
            style={{
              objectFit: "cover",
              width: "100%",
              height: "100%",
            }}
            unoptimized
          />
        </figure>
      )}
    </div>
  );
}
