import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, Search, X, UserCheck, UserX } from "lucide-react";
import { MOCK_USERS, type MockUser, type UserRole, type UserStatus } from "@/data/mockData";
import { StatusBadge } from "@/components/shared/StatusBadge";

const ROLES: UserRole[] = ["tenant_admin", "manager", "employee"];



export default function UsersPage() {
  const [users, setUsers] = useState(MOCK_USERS);
  const [search, setSearch] = useState("");
  const [showCreate, setShowCreate] = useState(false);
  const [newUser, setNewUser] = useState({ name: "", email: "", role: "employee" as UserRole });

  const filtered = users.filter(u =>
    u.name.toLowerCase().includes(search.toLowerCase()) ||
    u.email.toLowerCase().includes(search.toLowerCase())
  );

  const handleToggleStatus = (userId: number) => {
    setUsers(prev => prev.map(u => u.id === userId
      ? { ...u, status: u.status === "active" ? "suspended" : "active" as UserStatus }
      : u
    ));
  };

  const handleChangeRole = (userId: number, role: UserRole) => {
    setUsers(prev => prev.map(u => u.id === userId ? { ...u, role } : u));
  };

  const handleCreate = () => {
    if (!newUser.name.trim() || !newUser.email.trim()) return;
    const user: MockUser = {
      id: users.length + 100,
      tenantId: 1,
      tenantName: "Acme Corporation",
      name: newUser.name,
      email: newUser.email,
      role: newUser.role,
      status: "active",
      tasksAssigned: 0,
      tasksCompleted: 0,
      avatar: newUser.name.split(" ").map(n => n[0]).join("").slice(0, 2).toUpperCase(),
      createdAt: new Date().toISOString(),
    };
    setUsers(prev => [...prev, user]);
    setNewUser({ name: "", email: "", role: "employee" });
    setShowCreate(false);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Users</h1>
          <p className="text-sm text-muted-foreground mt-1">{users.filter(u => u.status === "active").length} active of {users.length} total</p>
        </div>
        <button
          onClick={() => setShowCreate(true)}
          className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg text-sm font-medium hover:bg-primary/90 transition"
          data-testid="button-create-user"
        >
          <Plus className="w-4 h-4" /> Add User
        </button>
      </div>

      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <input
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="Search users..."
          className="w-full pl-9 pr-4 py-2 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
        />
      </div>

      <div className="bg-card border border-card-border rounded-xl shadow-sm overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border bg-muted/30">
              <th className="text-left px-5 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">User</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Role</th>
              <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Status</th>
              <th className="text-center px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden md:table-cell">Assigned</th>
              <th className="text-center px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide hidden md:table-cell">Completed</th>
              <th className="text-right px-5 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wide">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((user, i) => (
              <motion.tr
                key={user.id}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: i * 0.05 }}
                className="border-b border-border/50 hover:bg-muted/20 transition-colors"
                data-testid={`row-user-${user.id}`}
              >
                <td className="px-5 py-3.5">
                  <div className="flex items-center gap-3">
                    <div className="w-9 h-9 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white text-xs font-bold flex-shrink-0">
                      {user.avatar}
                    </div>
                    <div>
                      <p className="font-medium text-foreground">{user.name}</p>
                      <p className="text-xs text-muted-foreground">{user.email}</p>
                    </div>
                  </div>
                </td>
                <td className="px-4 py-3.5">
                  <select
                    value={user.role}
                    onChange={e => handleChangeRole(user.id, e.target.value as UserRole)}
                    className="text-xs border border-border rounded-md px-2 py-1 bg-card focus:outline-none focus:ring-1 focus:ring-primary/30"
                  >
                    {ROLES.map(r => <option key={r} value={r}>{r.replace("_", " ")}</option>)}
                  </select>
                </td>
                <td className="px-4 py-3.5"><StatusBadge status={user.status} /></td>
                <td className="px-4 py-3.5 text-center hidden md:table-cell">
                  <span className="text-sm font-medium text-foreground">{user.tasksAssigned}</span>
                </td>
                <td className="px-4 py-3.5 text-center hidden md:table-cell">
                  <span className="text-sm font-medium text-emerald-600">{user.tasksCompleted}</span>
                </td>
                <td className="px-5 py-3.5 text-right">
                  <button
                    onClick={() => handleToggleStatus(user.id)}
                    title={user.status === "active" ? "Suspend user" : "Activate user"}
                    className={`p-1.5 rounded-lg transition ${user.status === "active" ? "text-muted-foreground hover:text-rose-500 hover:bg-rose-50" : "text-muted-foreground hover:text-emerald-600 hover:bg-emerald-50"}`}
                  >
                    {user.status === "active" ? <UserX className="w-4 h-4" /> : <UserCheck className="w-4 h-4" />}
                  </button>
                </td>
              </motion.tr>
            ))}
            {filtered.length === 0 && (
              <tr><td colSpan={6} className="px-5 py-12 text-center text-muted-foreground text-sm">No users found</td></tr>
            )}
          </tbody>
        </table>
      </div>

      <AnimatePresence>
        {showCreate && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4"
            onClick={() => setShowCreate(false)}
          >
            <motion.div initial={{ scale: 0.96, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.96, opacity: 0 }}
              onClick={e => e.stopPropagation()}
              className="bg-card rounded-2xl shadow-2xl w-full max-w-md overflow-hidden"
            >
              <div className="px-6 py-5 border-b border-border flex items-center justify-between">
                <h2 className="text-base font-semibold">Create User</h2>
                <button onClick={() => setShowCreate(false)} className="p-1.5 hover:bg-muted rounded text-muted-foreground"><X className="w-4 h-4" /></button>
              </div>
              <div className="p-6 space-y-4">
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Full Name *</label>
                  <input value={newUser.name} onChange={e => setNewUser(p => ({ ...p, name: e.target.value }))}
                    placeholder="John Smith"
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Email *</label>
                  <input type="email" value={newUser.email} onChange={e => setNewUser(p => ({ ...p, email: e.target.value }))}
                    placeholder="john@acme.corp"
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  />
                </div>
                <div>
                  <label className="text-xs font-medium text-muted-foreground mb-1.5 block">Role</label>
                  <select value={newUser.role} onChange={e => setNewUser(p => ({ ...p, role: e.target.value as UserRole }))}
                    className="w-full px-3 py-2.5 border border-border rounded-lg text-sm bg-card focus:outline-none focus:ring-2 focus:ring-primary/30"
                  >
                    {ROLES.map(r => <option key={r} value={r}>{r.replace("_", " ")}</option>)}
                  </select>
                </div>
                <div className="flex gap-3 pt-2">
                  <button onClick={() => setShowCreate(false)} className="flex-1 py-2.5 bg-muted text-muted-foreground text-sm font-medium rounded-lg">Cancel</button>
                  <button onClick={handleCreate} className="flex-1 py-2.5 bg-primary text-primary-foreground text-sm font-medium rounded-lg">Create User</button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
