'use client';

import { useEffect, useState } from 'react';
import { motion } from 'motion/react';

import { cn } from '@/lib/utils';

interface ServerStatus {
  online: boolean;
  players: {
    online: number;
    playerList?: string[];
  };
  uptime?: {
    days: number;
    hours: number;
    minutes: number;
    formatted: string;
  } | null;
  stats?: {
    totalPlayers: number;
    uniquePlayers7d: number;
    averageTps: string;
  };
  error?: string;
}

interface ServerStatusProps {
  className?: string;
}

type StatTile = {
  label: string;
  value: string;
  hint?: string;
};

export function ServerStatus({ className }: ServerStatusProps = {}) {
  const [status, setStatus] = useState<ServerStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStatus = async () => {
    try {
      const response = await fetch('/api/server-status');
      if (!response.ok) {
        throw new Error('Failed to fetch server status');
      }
      const data = await response.json() as ServerStatus;
      setStatus(data);
      setError(null);
    } catch (err) {
      setError('Failed to load server status');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatus();
    // Refresh every 30 seconds
    const interval = setInterval(fetchStatus, 30000);
    return () => clearInterval(interval);
  }, []);

  if (loading) {
    return (
      <div className="flex items-center gap-2 text-muted-foreground">
        <div className="h-2 w-2 rounded-full bg-muted" />
        <span>Loading server status...</span>
      </div>
    );
  }

  if (error || !status) {
    return (
      <div className="flex items-center gap-2 text-destructive">
        <div className="h-2 w-2 rounded-full bg-destructive" />
        <span>Unable to connect to server</span>
      </div>
    );
  }

  if (!status.online) {
    return (
      <div className="flex items-center gap-2 text-destructive">
        <div className="h-2 w-2 rounded-full bg-destructive" />
        <span>Server offline</span>
      </div>
    );
  }

  const statTiles: StatTile[] = [
    {
      label: 'Players Online',
      value: status.players.online.toString(),
      hint: 'right now',
    },
  ];

  if (status.uptime) {
    statTiles.push({
      label: 'Uptime',
      value: status.uptime.formatted,
      hint: 'since last restart',
    });
  }

  if (status.stats) {
    statTiles.push(
      {
        label: 'Total Players',
        value: status.stats.totalPlayers.toString(),
        hint: 'all-time',
      },
      {
        label: 'Unique (7d)',
        value: status.stats.uniquePlayers7d.toString(),
        hint: 'last week',
      }
    );
  }

  return (
    <motion.div
      className={cn(
        "space-y-6 rounded-2xl border border-border/50 bg-card/50 p-6 text-card-foreground shadow-xl backdrop-blur",
        className
      )}
      initial={{ opacity: 0, x: 20 }}
      animate={{ opacity: 1, x: 0 }}
      transition={{ duration: 0.5, delay: 0.3, ease: [0.33, 1, 0.68, 1] }}
      style={{ backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden", transform: "translateZ(0)" }}
    >
      <motion.div
        className="flex flex-wrap items-center justify-between gap-4"
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, delay: 0.5 }}
      >
        <div className="flex items-center gap-2.5">
          <span className="h-2 w-2 animate-pulse rounded-full bg-emerald-500 shadow-lg shadow-emerald-500/50" />
          <span className="text-sm font-bold text-emerald-600 dark:text-emerald-400">
            Server Online
          </span>
        </div>
        <span className="rounded-full border border-border/40 bg-background/70 px-3 py-1 text-[10px] font-bold uppercase tracking-[0.15em] text-muted-foreground shadow-sm">
          Refreshes every 30s
        </span>
      </motion.div>

      <motion.dl
        className="grid min-w-0 gap-3 sm:grid-cols-2"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ duration: 0.4, delay: 0.6, ease: [0.33, 1, 0.68, 1] }}
        style={{ backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden" }}
      >
        {statTiles.map((tile, index) => (
          <motion.div
            key={tile.label}
            className="group min-w-0 overflow-hidden rounded-xl border border-border/50 bg-background/95 p-4 shadow-md transition-all hover:border-primary/30 hover:shadow-lg"
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4, delay: 0.7 + index * 0.1, ease: [0.33, 1, 0.68, 1] }}
            style={{ backfaceVisibility: "hidden", WebkitBackfaceVisibility: "hidden", transform: "translateZ(0)" }}
          >
            <dt className="truncate text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">
              {tile.label}
            </dt>
            <dd className="mt-2 truncate text-2xl font-bold text-foreground">
              {tile.value}
            </dd>
            {tile.hint ? (
              <p className="mt-1 truncate text-[11px] font-medium uppercase tracking-[0.05em] text-muted-foreground/70">
                {tile.hint}
              </p>
            ) : null}
          </motion.div>
        ))}
      </motion.dl>

      {status.players.playerList && status.players.playerList.length > 0 && (
        <div className="rounded-xl border border-border/50 bg-background/95 p-4 shadow-md">
          <p className="mb-3 text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">
            Currently Online
          </p>
          <div className="flex flex-wrap gap-2">
            {status.players.playerList.map((player) => (
              <span
                key={player}
                className="rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-xs font-semibold text-primary shadow-sm"
              >
                {player}
              </span>
            ))}
          </div>
        </div>
      )}

      {status.stats?.averageTps ? (
        <div className="flex items-center justify-between rounded-xl border border-border/50 bg-background/95 px-4 py-3.5 shadow-md">
          <span className="text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">Average TPS (7d)</span>
          <span className="text-xl font-bold text-foreground">
            {status.stats.averageTps}
          </span>
        </div>
      ) : null}
    </motion.div>
  );
}
