"use client";

import { useState, useEffect, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Skeleton } from "@/components/ui/skeleton";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
  Search,
  MoreHorizontal,
  Ban,
  UserX,
  Shield,
  Clock,
  Users,
  WifiOff,
  RefreshCw,
} from "lucide-react";
import { toast } from "sonner";
import { formatDistanceToNow } from "date-fns";

interface Player {
  id: string;
  uuid: string | null;
  username: string;
  firstSeen: number;
  lastSeen: number;
  isOnline: boolean;
  playTime: number;
  role: string | null;
  isBanned: boolean;
  notes: string | null;
}

function PlayerAvatar({ username }: { username: string }) {
  return (
    <Avatar className="w-8 h-8">
      <AvatarImage
        src={`https://crafatar.com/avatars/${username}?size=32&overlay`}
        alt={username}
      />
      <AvatarFallback className="bg-zinc-800 text-zinc-400 text-xs">
        {username.slice(0, 2).toUpperCase()}
      </AvatarFallback>
    </Avatar>
  );
}

function formatPlayTime(minutes: number): string {
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  if (h === 0) return `${m}m`;
  return `${h}h ${m}m`;
}

export default function PlayersPage() {
  const [players, setPlayers] = useState<Player[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState<"all" | "online" | "banned">("all");
  const [selectedPlayer, setSelectedPlayer] = useState<Player | null>(null);
  const [banDialogOpen, setBanDialogOpen] = useState(false);
  const [banReason, setBanReason] = useState("");
  const [actionLoading, setActionLoading] = useState(false);

  const fetchPlayers = useCallback(async () => {
    try {
      const params = new URLSearchParams({ q: search, limit: "100" });
      if (filter === "online") params.set("online", "true");
      if (filter === "banned") params.set("banned", "true");
      const res = await fetch(`/api/players?${params}`);
      if (res.ok) {
        const data = await res.json();
        setPlayers(data.players);
      }
    } finally {
      setLoading(false);
    }
  }, [search, filter]);

  useEffect(() => {
    setLoading(true);
    fetchPlayers();
  }, [fetchPlayers]);

  const handleBan = async () => {
    if (!selectedPlayer || !banReason.trim()) return;
    setActionLoading(true);
    try {
      const res = await fetch(`/api/players/${selectedPlayer.id}?action=ban`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reason: banReason }),
      });
      if (!res.ok) throw new Error((await res.json()).error);
      toast.success(`${selectedPlayer.username} has been banned`);
      setBanDialogOpen(false);
      setBanReason("");
      fetchPlayers();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to ban player");
    } finally {
      setActionLoading(false);
    }
  };

  const handleUnban = async (player: Player) => {
    try {
      const res = await fetch(`/api/players/${player.id}?action=unban`, {
        method: "POST",
      });
      if (!res.ok) throw new Error((await res.json()).error);
      toast.success(`${player.username} has been unbanned`);
      fetchPlayers();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to unban player");
    }
  };

  const handleKick = async (player: Player) => {
    try {
      const res = await fetch(`/api/players/${player.id}?action=kick`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ reason: "Kicked by admin" }),
      });
      if (!res.ok) throw new Error((await res.json()).error);
      toast.success(`${player.username} has been kicked`);
      fetchPlayers();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to kick player");
    }
  };

  const onlinePlayers = players.filter((p) => p.isOnline).length;

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Players</h1>
          <p className="text-zinc-400 text-sm mt-1">
            Manage players, bans, and permissions
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30">
            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 mr-1.5 animate-pulse" />
            {onlinePlayers} online
          </Badge>
          <Button
            variant="outline"
            size="sm"
            className="border-zinc-700 text-zinc-400 hover:text-white"
            onClick={fetchPlayers}
          >
            <RefreshCw className="w-4 h-4" />
          </Button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" />
          <Input
            placeholder="Search players..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9 bg-zinc-900 border-zinc-700 text-white placeholder:text-zinc-500 focus:border-emerald-500/50"
          />
        </div>
        <div className="flex gap-2">
          {(["all", "online", "banned"] as const).map((f) => (
            <Button
              key={f}
              variant={filter === f ? "default" : "outline"}
              size="sm"
              onClick={() => setFilter(f)}
              className={
                filter === f
                  ? "bg-emerald-600 hover:bg-emerald-500 text-white"
                  : "border-zinc-700 text-zinc-400 hover:text-white"
              }
            >
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </Button>
          ))}
        </div>
      </div>

      {/* Players table */}
      <Card className="bg-zinc-900 border-zinc-800">
        <CardContent className="p-0">
          {loading ? (
            <div className="p-4 space-y-3">
              {Array.from({ length: 8 }).map((_, i) => (
                <Skeleton key={i} className="h-12 w-full bg-zinc-800" />
              ))}
            </div>
          ) : players.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-zinc-600">
              <Users className="w-10 h-10 mb-3 opacity-50" />
              <p>No players found</p>
            </div>
          ) : (
            <div className="divide-y divide-zinc-800">
              {/* Header */}
              <div className="grid grid-cols-[auto_1fr_auto_auto_auto_auto] gap-4 px-4 py-2.5 text-xs font-medium text-zinc-500 uppercase tracking-wide">
                <span className="w-8" />
                <span>Player</span>
                <span>Status</span>
                <span>Play Time</span>
                <span>Last Seen</span>
                <span />
              </div>

              {players.map((player) => (
                <div
                  key={player.id}
                  className="grid grid-cols-[auto_1fr_auto_auto_auto_auto] gap-4 px-4 py-3 items-center hover:bg-zinc-800/50 transition-colors"
                >
                  <PlayerAvatar username={player.username} />
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium text-white">
                        {player.username}
                      </span>
                      {player.role && (
                        <Badge
                          variant="outline"
                          className="text-xs border-zinc-700 text-zinc-400"
                        >
                          {player.role}
                        </Badge>
                      )}
                      {player.isBanned && (
                        <Badge className="text-xs bg-red-500/20 text-red-400 border-red-500/30">
                          Banned
                        </Badge>
                      )}
                    </div>
                    <span className="text-xs text-zinc-500">
                      {player.uuid ?? "UUID unknown"}
                    </span>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <span
                      className={`w-1.5 h-1.5 rounded-full ${
                        player.isOnline ? "bg-emerald-500" : "bg-zinc-600"
                      }`}
                    />
                    <span
                      className={`text-sm ${
                        player.isOnline ? "text-emerald-400" : "text-zinc-500"
                      }`}
                    >
                      {player.isOnline ? "Online" : "Offline"}
                    </span>
                  </div>
                  <span className="text-sm text-zinc-400">
                    {formatPlayTime(player.playTime)}
                  </span>
                  <span className="text-sm text-zinc-500">
                    {formatDistanceToNow(new Date(player.lastSeen), {
                      addSuffix: true,
                    })}
                  </span>
                  <DropdownMenu>
                    <DropdownMenuTrigger className="inline-flex shrink-0 items-center justify-center rounded-lg text-sm font-medium w-8 h-8 text-zinc-500 hover:text-white transition-all">
                      <MoreHorizontal className="w-4 h-4" />
                    </DropdownMenuTrigger>
                    <DropdownMenuContent
                      align="end"
                      className="bg-zinc-900 border-zinc-700"
                    >
                      <DropdownMenuItem
                        className="text-zinc-300 focus:text-white focus:bg-zinc-800"
                        onClick={() =>
                          (window.location.href = `/players/${player.id}`)
                        }
                      >
                        <Shield className="w-4 h-4 mr-2" />
                        View Profile
                      </DropdownMenuItem>
                      {player.isOnline && (
                        <DropdownMenuItem
                          className="text-amber-400 focus:text-amber-300 focus:bg-zinc-800"
                          onClick={() => handleKick(player)}
                        >
                          <WifiOff className="w-4 h-4 mr-2" />
                          Kick
                        </DropdownMenuItem>
                      )}
                      <DropdownMenuSeparator className="bg-zinc-700" />
                      {player.isBanned ? (
                        <DropdownMenuItem
                          className="text-emerald-400 focus:text-emerald-300 focus:bg-zinc-800"
                          onClick={() => handleUnban(player)}
                        >
                          <UserX className="w-4 h-4 mr-2" />
                          Unban
                        </DropdownMenuItem>
                      ) : (
                        <DropdownMenuItem
                          className="text-red-400 focus:text-red-300 focus:bg-zinc-800"
                          onClick={() => {
                            setSelectedPlayer(player);
                            setBanDialogOpen(true);
                          }}
                        >
                          <Ban className="w-4 h-4 mr-2" />
                          Ban
                        </DropdownMenuItem>
                      )}
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Ban Dialog */}
      <Dialog open={banDialogOpen} onOpenChange={setBanDialogOpen}>
        <DialogContent className="bg-zinc-900 border-zinc-700">
          <DialogHeader>
            <DialogTitle className="text-white">
              Ban {selectedPlayer?.username}
            </DialogTitle>
            <DialogDescription className="text-zinc-400">
              This will ban the player from the server and record the ban in the
              history.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <Label className="text-zinc-300">Reason</Label>
            <Textarea
              value={banReason}
              onChange={(e) => setBanReason(e.target.value)}
              placeholder="Enter ban reason..."
              className="bg-zinc-800 border-zinc-700 text-white placeholder:text-zinc-500 resize-none"
              rows={3}
            />
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setBanDialogOpen(false)}
              className="border-zinc-700 text-zinc-400"
            >
              Cancel
            </Button>
            <Button
              onClick={handleBan}
              disabled={!banReason.trim() || actionLoading}
              className="bg-red-600 hover:bg-red-500 text-white"
            >
              {actionLoading ? "Banning..." : "Ban Player"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
