"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { NewUserDialog } from "./NewUserDialog";
import { EditUserDialog, type EditableUser } from "./EditUserDialog";
import { useRouter } from "next/navigation";
import { PlusCircle, Pencil, ShieldCheck, Shield, Eye, Palette, User2, Trash2 } from "lucide-react";
import { deleteUser } from "@/actions/users";

const ROLE_CONFIG: Record<string, { label: string; className: string; Icon: React.ElementType }> = {
  ADMIN:      { label: "Admin",      className: "bg-red-500/10 text-red-400 border border-red-500/20",         Icon: ShieldCheck },
  PRODUCER:   { label: "Producer",   className: "bg-blue-500/10 text-blue-400 border border-blue-500/20",      Icon: Shield },
  SUPERVISOR: { label: "Supervisor", className: "bg-violet-500/10 text-violet-400 border border-violet-500/20", Icon: Eye },
  ARTIST:     { label: "Artist",     className: "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20", Icon: Palette },
  CLIENT:     { label: "Client",     className: "bg-zinc-500/10 text-zinc-400 border border-zinc-500/20",      Icon: User2 },
};

function getInitials(name: string | null, email: string) {
  const src = name ?? email;
  return src.slice(0, 2).toUpperCase();
}

interface User {
  id: string;
  name: string | null;
  email: string;
  role: string;
  isActive: boolean;
  createdAt: string;
}

interface UsersClientProps {
  users: User[];
  currentUserId: string;
}

export function UsersClient({ users, currentUserId }: UsersClientProps) {
  const router = useRouter();
  const [showNew, setShowNew] = useState(false);
  const [editTarget, setEditTarget] = useState<EditableUser | null>(null);
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
  const [deleting, setDeleting] = useState(false);

  const handleSuccess = () => {
    router.refresh();
  };

  async function handleDelete(userId: string) {
    setDeleting(true);
    try {
      await deleteUser(userId);
      router.refresh();
    } finally {
      setDeleting(false);
      setConfirmDeleteId(null);
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <p className="text-sm text-zinc-400">
          {users.length} user{users.length !== 1 ? "s" : ""}
        </p>
        <Button className="gap-2" onClick={() => setShowNew(true)}>
          <PlusCircle className="h-4 w-4" />
          New User
        </Button>
      </div>

      {/* Table */}
      <div className="rounded-xl border border-zinc-800 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-zinc-900 border-b border-zinc-800">
            <tr>
              <th className="px-4 py-3 text-left font-medium text-zinc-400">User</th>
              <th className="px-4 py-3 text-left font-medium text-zinc-400">Role</th>
              <th className="px-4 py-3 text-left font-medium text-zinc-400">Status</th>
              <th className="px-4 py-3 text-right font-medium text-zinc-400"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-zinc-800">
            {users.map((user) => {
              const role = ROLE_CONFIG[user.role] ?? ROLE_CONFIG.ARTIST;
              const RoleIcon = role.Icon;
              const isSelf = user.id === currentUserId;
              return (
                <tr key={user.id} className={cn("bg-zinc-950 hover:bg-zinc-900/60 transition-colors", !user.isActive && "opacity-50")}>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <div className="h-8 w-8 rounded-full bg-zinc-800 border border-zinc-700 flex items-center justify-center shrink-0 text-xs font-semibold text-zinc-300">
                        {getInitials(user.name, user.email)}
                      </div>
                      <div>
                        <p className="font-medium text-white">
                          {user.name ?? <span className="text-zinc-500 italic">No name</span>}
                          {isSelf && <span className="ml-2 text-xs text-amber-400 font-normal">(you)</span>}
                        </p>
                        <p className="text-xs text-zinc-500">{user.email}</p>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className={cn("inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium", role.className)}>
                      <RoleIcon className="h-3 w-3" />
                      {role.label}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={cn(
                      "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border",
                      user.isActive
                        ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20"
                        : "bg-zinc-700/30 text-zinc-500 border-zinc-700/50"
                    )}>
                      <span className={cn("h-1.5 w-1.5 rounded-full", user.isActive ? "bg-emerald-400" : "bg-zinc-500")} />
                      {user.isActive ? "Active" : "Inactive"}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-right">
                    <div className="flex items-center justify-end gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="gap-1.5 h-7 text-zinc-400 hover:text-zinc-100"
                        onClick={() => setEditTarget({ id: user.id, name: user.name, email: user.email, role: user.role, isActive: user.isActive })}
                      >
                        <Pencil className="h-3.5 w-3.5" />
                        Edit
                      </Button>
                      {!isSelf && (
                        confirmDeleteId === user.id ? (
                          <>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 text-zinc-400 hover:text-zinc-100"
                              onClick={() => setConfirmDeleteId(null)}
                              disabled={deleting}
                            >
                              Cancel
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 text-red-400 hover:text-red-300 hover:bg-red-500/10"
                              onClick={() => handleDelete(user.id)}
                              disabled={deleting}
                            >
                              {deleting ? "Deleting…" : "Confirm delete"}
                            </Button>
                          </>
                        ) : (
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-7 text-zinc-600 hover:text-red-400 hover:bg-red-500/10"
                            onClick={() => setConfirmDeleteId(user.id)}
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        )
                      )}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <NewUserDialog open={showNew} onClose={() => setShowNew(false)} onSuccess={handleSuccess} />

      {editTarget && (
        <EditUserDialog
          user={editTarget}
          isSelf={editTarget.id === currentUserId}
          open={!!editTarget}
          onClose={() => setEditTarget(null)}
          onSuccess={() => { setEditTarget(null); handleSuccess(); }}
        />
      )}
    </div>
  );
}
