import { useState, useEffect } from "react";
import { Loader2, AlertCircle } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";

export default function Metaset() {
  const [isLoading, setIsLoading] = useState(true);
  const [hasError, setHasError] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  useEffect(() => {
    // Verificar se o Metaset está online
    fetch("/api/bi/metaset/health", { credentials: "include" })
      .then(r => r.json())
      .then(data => {
        if (!data.online) {
          setHasError(true);
          setErrorMessage("O Metaset está offline ou iniciando.");
        }
      })
      .catch(() => {
        setHasError(true);
        setErrorMessage("Não foi possível conectar ao Metaset.");
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, []);

  if (hasError) {
    return (
      <div className="h-[calc(100vh-40px)] w-full flex items-center justify-center p-4">
        <Alert variant="destructive" className="max-w-md">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            {errorMessage}
            <div className="mt-4">
              <Button onClick={() => window.location.reload()}>
                Tentar novamente
              </Button>
            </div>
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  return (
    <div className="h-[calc(100vh-40px)] w-full relative">
      {isLoading && (
        <div className="absolute inset-0 flex items-center justify-center bg-background z-10">
          <div className="flex flex-col items-center gap-2">
            <Loader2 className="w-8 h-8 animate-spin text-primary" />
            <span className="text-sm text-muted-foreground">Carregando Metaset...</span>
          </div>
        </div>
      )}
      <iframe
        src="/metaset"
        className="w-full h-full border-0"
        onLoad={() => setIsLoading(false)}
        title="Metaset BI"
      />
    </div>
  );
}
