"use client";

import { useEffect, useState, useCallback } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { UserPlus, Mail, Clock, RefreshCw } from "lucide-react";
import { toast } from "sonner";
import { formatDistanceToNow } from "date-fns";

interface TeamUser {
  id: string;
  name: string;
  email: string;
  role: string | null;
  createdAt: number;
  image: string | null;
}

interface PendingInvite {
  id: string;
  email: string;
  role: string;
  expiresAt: number;
  createdAt: number;
}

const ROLE_CONFIG: Record<string, { label: string; color: string }> = {
  superadmin: { label: "Super Admin", color: "bg-amber-500/20 text-amber-400 border-amber-500/30" },
  admin: { label: "Admin", color: "bg-blue-500/20 text-blue-400 border-blue-500/30" },
  moderator: { label: "Moderator", color: "bg-violet-500/20 text-violet-400 border-violet-500/30" },
};

export default function TeamPage() {
  const [users, setUsers] = useState<TeamUser[]>([]);
  const [invites, setInvites] = useState<PendingInvite[]>([]);
  const [loading, setLoading] = useState(true);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteRole, setInviteRole] = useState<"admin" | "moderator">("moderator");
  const [inviting, setInviting] = useState(false);

  const fetchTeam = useCallback(async () => {
    try {
      const res = await fetch("/api/team");
      if (res.ok) {
        const data = await res.json();
        setUsers(data.users);
        setInvites(data.pendingInvites ?? []);
      }
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchTeam(); }, [fetchTeam]);

  const handleInvite = async () => {
    if (!inviteEmail) return;
    setInviting(true);
    try {
      const res = await fetch("/api/team", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: inviteEmail, role: inviteRole }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      toast.success(`Invitation sent to ${inviteEmail}`);
      setInviteOpen(false);
      setInviteEmail("");
      fetchTeam();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to send invitation");
    } finally {
      setInviting(false);
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Team</h1>
          <p className="text-zinc-400 text-sm mt-1">
            Manage who can access the CubeAdmin panel
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={fetchTeam} className="border-zinc-700 text-zinc-400 hover:text-white">
            <RefreshCw className="w-4 h-4" />
          </Button>
          <Button size="sm" className="bg-emerald-600 hover:bg-emerald-500 text-white" onClick={() => setInviteOpen(true)}>
            <UserPlus className="w-4 h-4 mr-1.5" />
            Invite Member
          </Button>
        </div>
      </div>

      {/* Active members */}
      <Card className="bg-zinc-900 border-zinc-800">
        <CardContent className="p-0">
          {loading ? (
            <div className="p-4 space-y-3">
              {[1, 2, 3].map(i => <Skeleton key={i} className="h-14 w-full bg-zinc-800" />)}
            </div>
          ) : (
            <div className="divide-y divide-zinc-800">
              <div className="px-4 py-2.5 text-xs font-medium text-zinc-500 uppercase tracking-wide">
                Active Members ({users.length})
              </div>
              {users.map(user => (
                <div key={user.id} className="flex items-center gap-4 px-4 py-3 hover:bg-zinc-800/50 transition-colors">
                  <Avatar className="w-9 h-9 shrink-0">
                    <AvatarImage src={user.image ?? undefined} />
                    <AvatarFallback className="bg-zinc-800 text-zinc-400 text-sm">
                      {user.name?.slice(0, 2).toUpperCase()}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-white">{user.name}</p>
                    <p className="text-xs text-zinc-500 truncate">{user.email}</p>
                  </div>
                  <Badge className={`text-xs ${ROLE_CONFIG[user.role ?? ""]?.color ?? "bg-zinc-500/20 text-zinc-400"}`}>
                    {ROLE_CONFIG[user.role ?? ""]?.label ?? user.role ?? "No role"}
                  </Badge>
                  <p className="text-xs text-zinc-600 hidden sm:block shrink-0">
                    Joined {formatDistanceToNow(new Date(user.createdAt), { addSuffix: true })}
                  </p>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pending invites */}
      {invites.length > 0 && (
        <Card className="bg-zinc-900 border-zinc-800 border-dashed">
          <CardContent className="p-0">
            <div className="divide-y divide-zinc-800">
              <div className="px-4 py-2.5 text-xs font-medium text-zinc-500 uppercase tracking-wide">
                Pending Invitations ({invites.length})
              </div>
              {invites.map(invite => (
                <div key={invite.id} className="flex items-center gap-4 px-4 py-3">
                  <div className="w-9 h-9 rounded-full bg-zinc-800 flex items-center justify-center shrink-0">
                    <Mail className="w-4 h-4 text-zinc-500" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-zinc-300">{invite.email}</p>
                    <p className="text-xs text-zinc-500 flex items-center gap-1 mt-0.5">
                      <Clock className="w-3 h-3" />
                      Expires {formatDistanceToNow(new Date(invite.expiresAt), { addSuffix: true })}
                    </p>
                  </div>
                  <Badge className={`text-xs ${ROLE_CONFIG[invite.role]?.color ?? ""}`}>
                    {ROLE_CONFIG[invite.role]?.label ?? invite.role}
                  </Badge>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* Invite dialog */}
      <Dialog open={inviteOpen} onOpenChange={setInviteOpen}>
        <DialogContent className="bg-zinc-900 border-zinc-700">
          <DialogHeader>
            <DialogTitle className="text-white">Invite Team Member</DialogTitle>
            <DialogDescription className="text-zinc-400">
              They&apos;ll receive an email with a link to create their account.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-1.5">
              <Label className="text-zinc-300">Email Address</Label>
              <Input
                type="email"
                value={inviteEmail}
                onChange={(e) => setInviteEmail(e.target.value)}
                placeholder="teammate@example.com"
                className="bg-zinc-800 border-zinc-700 text-white placeholder:text-zinc-500 focus:border-emerald-500/50"
              />
            </div>
            <div className="space-y-1.5">
              <Label className="text-zinc-300">Role</Label>
              <Select value={inviteRole} onValueChange={(v) => { if (v === "admin" || v === "moderator") setInviteRole(v); }}>
                <SelectTrigger className="bg-zinc-800 border-zinc-700 text-white">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="admin" className="text-zinc-300 focus:bg-zinc-700 focus:text-white">
                    Admin — Full access except team management
                  </SelectItem>
                  <SelectItem value="moderator" className="text-zinc-300 focus:bg-zinc-700 focus:text-white">
                    Moderator — Player management only
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setInviteOpen(false)} className="border-zinc-700 text-zinc-400">
              Cancel
            </Button>
            <Button
              onClick={handleInvite}
              disabled={!inviteEmail || inviting}
              className="bg-emerald-600 hover:bg-emerald-500 text-white"
            >
              {inviting ? "Sending..." : "Send Invitation"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
