'use client';

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

import { cn } from '@/lib/utils';
import { Skeleton } from '@/components/ui/skeleton';

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={cn("space-y-6 rounded-2xl border border-border/50 bg-card/50 p-6 shadow-xl backdrop-blur", className)}>
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-2.5">
            <Skeleton className="h-3 w-3 rounded-full" />
            <Skeleton className="h-4 w-24" />
          </div>
          <Skeleton className="h-5 w-32 rounded-full" />
        </div>
        <div className="grid min-w-0 gap-3 sm:grid-cols-2">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="rounded-xl border border-border/50 bg-background/95 p-4">
              <Skeleton className="h-3 w-20 mb-2" />
              <Skeleton className="h-8 w-16 mb-1" />
              <Skeleton className="h-2 w-12" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  if (error || !status) {
    return (
      <motion.div
        className={cn(
          "space-y-6 rounded-2xl border border-destructive/50 bg-destructive/10 p-6 text-card-foreground shadow-xl backdrop-blur",
          className
        )}
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 0.3 }}
      >
        <motion.div
          className="flex items-center gap-3 rounded-xl border border-destructive/50 bg-destructive/20 px-4 py-3"
          animate={{
            boxShadow: [
              '0 0 0px rgba(239, 68, 68, 0.4)',
              '0 0 20px rgba(239, 68, 68, 0.6)',
              '0 0 0px rgba(239, 68, 68, 0.4)',
            ],
          }}
          transition={{
            duration: 2,
            repeat: Number.POSITIVE_INFINITY,
            ease: 'easeInOut',
          }}
        >
          <motion.div
            className="h-3 w-3 rounded-full bg-destructive"
            animate={{
              scale: [1, 1.2, 1],
              opacity: [1, 0.7, 1],
            }}
            transition={{
              duration: 1.5,
              repeat: Number.POSITIVE_INFINITY,
              ease: 'easeInOut',
            }}
          />
          <span className="text-sm font-bold text-destructive">Unable to connect to server</span>
        </motion.div>
      </motion.div>
    );
  }

  if (!status.online) {
    return (
      <motion.div
        className={cn(
          "space-y-6 rounded-2xl border border-destructive/50 bg-destructive/10 p-6 text-card-foreground shadow-xl backdrop-blur",
          className
        )}
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ 
          opacity: 1, 
          scale: 1,
          x: [0, -2, 2, -2, 2, 0],
        }}
        transition={{ 
          duration: 0.5,
          x: {
            duration: 0.3,
            repeat: 0,
          },
        }}
      >
        <motion.div
          className="flex items-center gap-3 rounded-xl border border-destructive/50 bg-destructive/20 px-4 py-3"
          animate={{
            boxShadow: [
              '0 0 0px rgba(239, 68, 68, 0.4)',
              '0 0 20px rgba(239, 68, 68, 0.6)',
              '0 0 0px rgba(239, 68, 68, 0.4)',
            ],
          }}
          transition={{
            duration: 2,
            repeat: Number.POSITIVE_INFINITY,
            ease: 'easeInOut',
          }}
        >
          <motion.div
            className="h-3 w-3 rounded-full bg-destructive"
            animate={{
              scale: [1, 1.3, 1],
              opacity: [1, 0.6, 1],
            }}
            transition={{
              duration: 1.5,
              repeat: Number.POSITIVE_INFINITY,
              ease: 'easeInOut',
            }}
          />
          <span className="text-sm font-bold text-destructive">Server Offline</span>
        </motion.div>
        <p className="text-xs text-muted-foreground text-center">
          The server is currently unavailable. Please check back later.
        </p>
      </motion.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-5 text-card-foreground",
        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">
          <motion.span
            className="h-3 w-3 rounded-full bg-primary shadow-lg"
            animate={{
              scale: [1, 1.2, 1],
              opacity: [1, 0.8, 1],
            }}
            transition={{
              duration: 2,
              repeat: Number.POSITIVE_INFINITY,
              ease: 'easeInOut',
            }}
          />
          <motion.span 
            className="text-sm font-bold text-primary"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.6 }}
          >
            Server Online
          </motion.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-4 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-5 shadow-md backdrop-blur-sm transition-all duration-200 ease-out hover:scale-[1.02] hover:border-primary/30 hover:shadow-lg noise-texture"
            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="text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground break-words">
              {tile.label}
            </dt>
            <dd className={cn(
              "mt-3 text-2xl font-bold break-words break-all",
              (tile.label === 'Players Online' || tile.label === 'Total Players') 
                ? "text-primary" 
                : "text-foreground"
            )}>
              {tile.value}
            </dd>
            {tile.hint ? (
              <p className="mt-2 text-[11px] font-medium uppercase tracking-[0.05em] text-muted-foreground/70 break-words">
                {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-5 py-4 shadow-md backdrop-blur-sm transition-all duration-200 ease-out hover:scale-[1.02] hover:border-primary/30 hover:shadow-lg noise-texture">
          <span className="text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">Average TPS (7d)</span>
          <span className="text-2xl font-bold text-foreground">
            {status.stats.averageTps}
          </span>
        </div>
      ) : null}
    </motion.div>
  );
}
