"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Map, ExternalLink, AlertCircle } from "lucide-react";
import { Button, buttonVariants } from "@/components/ui/button";

export default function MapPage() {
  const [bluemapUrl, setBluemapUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [iframeLoaded, setIframeLoaded] = useState(false);
  const [iframeError, setIframeError] = useState(false);

  useEffect(() => {
    // Fetch BlueMap URL from server settings
    fetch("/api/server/settings")
      .then((r) => r.json())
      .then((data) => {
        setBluemapUrl(data?.settings?.bluemapUrl ?? null);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="p-6 space-y-6">
        <Skeleton className="h-8 w-48 bg-zinc-800" />
        <Skeleton className="h-[70vh] w-full bg-zinc-800 rounded-xl" />
      </div>
    );
  }

  if (!bluemapUrl) {
    return (
      <div className="p-6 space-y-6">
        <div>
          <h1 className="text-2xl font-bold text-white">3D World Map</h1>
          <p className="text-zinc-400 text-sm mt-1">
            Interactive BlueMap integration
          </p>
        </div>
        <Card className="bg-zinc-900 border-zinc-800">
          <CardContent className="flex flex-col items-center justify-center py-20">
            <Map className="w-12 h-12 text-zinc-600 mb-4" />
            <h3 className="text-white font-semibold mb-2">
              BlueMap not configured
            </h3>
            <p className="text-zinc-500 text-sm text-center max-w-md mb-6">
              BlueMap is a 3D world map plugin for Minecraft servers. Configure
              its URL in <strong>Server Settings</strong> to embed it here.
            </p>
            <a href="/server" className={buttonVariants({ className: "bg-emerald-600 hover:bg-emerald-500 text-white" })}>Go to Server Settings</a>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-4 h-full flex flex-col">
      <div className="flex items-center justify-between shrink-0">
        <div>
          <h1 className="text-2xl font-bold text-white">3D World Map</h1>
          <p className="text-zinc-400 text-sm mt-1">
            Powered by BlueMap — live world view with player positions
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-xs">
            BlueMap
          </Badge>
          <a href={bluemapUrl} target="_blank" rel="noopener noreferrer" className={buttonVariants({ variant: "outline", size: "sm", className: "border-zinc-700 text-zinc-400 hover:text-white" })}>
            <ExternalLink className="w-4 h-4 mr-1.5" />
            Open in new tab
          </a>
        </div>
      </div>

      <div className="flex-1 min-h-0 rounded-xl border border-zinc-800 overflow-hidden bg-zinc-950 relative">
        {!iframeLoaded && !iframeError && (
          <div className="absolute inset-0 flex items-center justify-center bg-zinc-950 z-10">
            <div className="flex flex-col items-center gap-3 text-zinc-500">
              <div className="w-8 h-8 border-2 border-emerald-500/30 border-t-emerald-500 rounded-full animate-spin" />
              <p className="text-sm">Loading BlueMap...</p>
            </div>
          </div>
        )}
        {iframeError && (
          <div className="absolute inset-0 flex items-center justify-center bg-zinc-950 z-10">
            <div className="flex flex-col items-center gap-3 text-zinc-500 max-w-sm text-center">
              <AlertCircle className="w-10 h-10 text-amber-500" />
              <p className="text-white font-medium">Could not load BlueMap</p>
              <p className="text-sm">
                Make sure BlueMap is running at{" "}
                <code className="text-emerald-400 text-xs">{bluemapUrl}</code>{" "}
                and that the URL is accessible from your browser.
              </p>
              <Button
                variant="outline"
                size="sm"
                className="border-zinc-700 text-zinc-400"
                onClick={() => {
                  setIframeError(false);
                  setIframeLoaded(false);
                }}
              >
                Retry
              </Button>
            </div>
          </div>
        )}
        <iframe
          src={bluemapUrl}
          className="w-full h-full border-0"
          style={{ minHeight: "600px" }}
          onLoad={() => setIframeLoaded(true)}
          onError={() => setIframeError(true)}
          title="BlueMap 3D World Map"
          sandbox="allow-scripts allow-same-origin allow-forms"
        />
      </div>
    </div>
  );
}
