"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Search, Filter, Eye, Loader2 } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Progress } from "@/components/ui/progress";
import { formatDate, getInitials } from "@/lib/utils";
import { getPlanBadgeColor, PLAN_LIMITS } from "@/lib/plan-limits";
import { adminApi, type AdminUserResponse, type Plan } from "@/lib/api";
import { getAdminToken } from "@/lib/admin-store";

export default function AdminUsersPage() {
  const router = useRouter();
  const [users, setUsers] = useState<AdminUserResponse[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [planFilter, setPlanFilter] = useState("all");
  const [selectedUser, setSelectedUser] = useState<AdminUserResponse | null>(null);
  const [updatingPlan, setUpdatingPlan] = useState<number | null>(null);

  useEffect(() => {
    (async () => {
      const token = await getAdminToken();
      if (!token) { router.push("/admin-login"); return; }
      try {
        setUsers(await adminApi.getUsers(token));
      } catch {
        router.push("/admin-login");
      } finally {
        setLoading(false);
      }
    })();
  }, [router]);

  const handlePlanChange = async (userId: number, plan: Plan) => {
    const token = await getAdminToken();
    if (!token) return;
    setUpdatingPlan(userId);
    try {
      const updated = await adminApi.updateUserPlan(token, userId, plan);
      setUsers((prev) => prev.map((u) => (u.id === userId ? { ...u, plan: updated.plan } : u)));
      if (selectedUser?.id === userId) setSelectedUser({ ...selectedUser, plan: updated.plan });
    } catch {
      // ignore
    } finally {
      setUpdatingPlan(null);
    }
  };

  const handleToggleActive = async (userId: number, currentActive: boolean) => {
    const token = await getAdminToken();
    if (!token) return;
    try {
      const updated = await adminApi.toggleUserActive(token, userId, !currentActive);
      setUsers((prev) => prev.map((u) => (u.id === userId ? { ...u, is_active: updated.is_active } : u)));
      if (selectedUser?.id === userId) setSelectedUser({ ...selectedUser, is_active: updated.is_active });
    } catch {
      // ignore
    }
  };

  const filtered = users.filter((u) => {
    const matchSearch =
      u.name.toLowerCase().includes(search.toLowerCase()) ||
      u.email.toLowerCase().includes(search.toLowerCase());
    const matchPlan = planFilter === "all" || u.plan === planFilter;
    return matchSearch && matchPlan;
  });

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20 text-zinc-500">
        <Loader2 className="w-5 h-5 animate-spin mr-2" /> Loading users...
      </div>
    );
  }

  return (
    <div>
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-white">Users</h1>
        <p className="text-zinc-500 text-sm mt-1">{users.length} registered users</p>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3 mb-6">
        <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 by name or email..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9 bg-white/5 border-white/10 text-white placeholder:text-zinc-600"
          />
        </div>
        <Select value={planFilter} onValueChange={(v) => setPlanFilter(v ?? "all")}>
          <SelectTrigger className="w-40 bg-white/5 border-white/10 text-white">
            <Filter className="w-4 h-4 mr-2 text-zinc-500" />
            <SelectValue />
          </SelectTrigger>
          <SelectContent className="bg-zinc-900 border-white/10">
            <SelectItem value="all">All Plans</SelectItem>
            <SelectItem value="free">Free</SelectItem>
            <SelectItem value="pro">Pro</SelectItem>
            <SelectItem value="pro_max">Pro Max</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Table */}
      <div className="glass-card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-white/8">
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">User</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Plan</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Joined</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Status</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Total Jobs</th>
                <th className="text-left px-5 py-3.5 text-xs font-medium text-zinc-500">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((user) => (
                <tr key={user.id} className="border-b border-white/5 hover:bg-white/3 transition-colors">
                  <td className="px-5 py-4">
                    <div className="flex items-center gap-3">
                      <div className="w-9 h-9 rounded-full bg-gradient-to-br from-violet-600 to-cyan-500 flex items-center justify-center text-sm font-bold text-white flex-shrink-0">
                        {getInitials(user.name)}
                      </div>
                      <div>
                        <div className="flex items-center gap-2">
                          <div className="text-sm font-medium text-white">{user.name}</div>
                          {user.is_admin && (
                            <Badge className="text-[10px] bg-red-500/15 text-red-400 border-red-500/30 px-1.5 py-0">Admin</Badge>
                          )}
                        </div>
                        <div className="text-xs text-zinc-500">{user.email}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-5 py-4">
                    <Select
                      value={user.plan}
                      onValueChange={(v) => handlePlanChange(user.id, v as Plan)}
                      disabled={updatingPlan === user.id}
                    >
                      <SelectTrigger className="w-28 h-7 bg-transparent border-white/10 text-xs">
                        <Badge className={`text-xs ${getPlanBadgeColor(user.plan)}`}>
                          {PLAN_LIMITS[user.plan].name}
                        </Badge>
                      </SelectTrigger>
                      <SelectContent className="bg-zinc-900 border-white/10">
                        <SelectItem value="free">Free</SelectItem>
                        <SelectItem value="pro">Pro</SelectItem>
                        <SelectItem value="pro_max">Pro Max</SelectItem>
                      </SelectContent>
                    </Select>
                  </td>
                  <td className="px-5 py-4 text-sm text-zinc-400">{formatDate(user.created_at)}</td>
                  <td className="px-5 py-4">
                    <button
                      onClick={() => handleToggleActive(user.id, user.is_active)}
                      className="focus:outline-none"
                    >
                      <Badge
                        className={
                          user.is_active
                            ? "bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs cursor-pointer hover:bg-emerald-500/25"
                            : "bg-zinc-800 text-zinc-400 border-zinc-700 text-xs cursor-pointer hover:bg-zinc-700"
                        }
                      >
                        {user.is_active ? "active" : "disabled"}
                      </Badge>
                    </button>
                  </td>
                  <td className="px-5 py-4 text-sm text-zinc-400">{user.total_jobs}</td>
                  <td className="px-5 py-4">
                    <Button
                      size="sm"
                      variant="ghost"
                      className="h-7 text-xs text-zinc-400 hover:text-white"
                      onClick={() => setSelectedUser(user)}
                    >
                      <Eye className="w-3.5 h-3.5 mr-1" />
                      View
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="px-5 py-3 border-t border-white/8">
          <p className="text-xs text-zinc-500">
            Showing {filtered.length} of {users.length} users
          </p>
        </div>
      </div>

      {/* User Detail Modal */}
      <Dialog open={!!selectedUser} onOpenChange={() => setSelectedUser(null)}>
        <DialogContent className="bg-zinc-900 border-white/10 text-white max-w-md">
          <DialogHeader>
            <DialogTitle>User Details</DialogTitle>
          </DialogHeader>
          {selectedUser && (
            <div className="space-y-4">
              <div className="flex items-center gap-4">
                <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-violet-600 to-cyan-500 flex items-center justify-center text-xl font-bold text-white">
                  {getInitials(selectedUser.name)}
                </div>
                <div>
                  <div className="font-semibold">{selectedUser.name}</div>
                  <div className="text-sm text-zinc-400">{selectedUser.email}</div>
                  <Badge className={`mt-1 text-xs ${getPlanBadgeColor(selectedUser.plan)}`}>
                    {PLAN_LIMITS[selectedUser.plan].name}
                  </Badge>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div className="bg-white/5 rounded-lg p-3">
                  <div className="text-2xl font-bold">{selectedUser.total_jobs}</div>
                  <div className="text-xs text-zinc-500">Total Jobs</div>
                </div>
                <div className="bg-white/5 rounded-lg p-3">
                  <div className="text-2xl font-bold">{selectedUser.videos_used_today}</div>
                  <div className="text-xs text-zinc-500">Used Today</div>
                </div>
              </div>
              <div className="space-y-2">
                <div className="flex justify-between text-xs">
                  <span className="text-zinc-500">Daily Usage</span>
                  <span className="text-zinc-300">
                    {selectedUser.videos_used_today} /{" "}
                    {PLAN_LIMITS[selectedUser.plan].videos_per_day === Infinity
                      ? "∞"
                      : PLAN_LIMITS[selectedUser.plan].videos_per_day}
                  </span>
                </div>
                <Progress
                  value={
                    PLAN_LIMITS[selectedUser.plan].videos_per_day === Infinity
                      ? 10
                      : (selectedUser.videos_used_today / PLAN_LIMITS[selectedUser.plan].videos_per_day) * 100
                  }
                  className="h-2 bg-white/10"
                />
              </div>
              <div className="text-xs text-zinc-500 space-y-1.5 pt-1">
                <div className="flex justify-between">
                  <span>Joined</span>
                  <span className="text-zinc-300">{formatDate(selectedUser.created_at)}</span>
                </div>
                <div className="flex justify-between">
                  <span>Status</span>
                  <span className={selectedUser.is_active ? "text-emerald-400" : "text-red-400"}>
                    {selectedUser.is_active ? "Active" : "Disabled"}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span>Role</span>
                  <span className="text-zinc-300">{selectedUser.is_admin ? "Admin" : "User"}</span>
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
