import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, X, Shield, Users, Trash2 } from "lucide-react";
import { MOCK_ROLES, type MockRole } from "@/data/mockData";

const ALL_PERMISSIONS = [
  { key: "tasks:manage", label: "Manage Tasks" },
  { key: "tasks:read", label: "View Tasks" },
  { key: "tasks:update", label: "Update Tasks" },
  { key: "users:manage", label: "Manage Users" },
  { key: "users:read", label: "View Users" },
  { key: "documents:manage", label: "Manage Documents" },
  { key: "documents:read", label: "View Documents" },
  { key: "billing:manage", label: "Manage Billing" },
  { key: "roles:manage", label: "Manage Roles" },
];

export default function RolesPage() {
  const [roles, setRoles] = useState(MOCK_ROLES);
  const [showCreate, setShowCreate] = useState(false);
  const [newRole, setNewRole] = useState({ name: "", description: "", permissions: [] as string[] });

  const togglePermission = (perm: string) => {
    setNewRole(p => ({
      ...p,
      permissions: p.permissions.includes(perm)
        ? p.permissions.filter(x => x !== perm)
        : [...p.permissions, perm],
    }));
  };

  const handleCreate = () => {
    if (!newRole.name.trim()) return;
    const role: MockRole = {
      id: roles.length + 100,
      tenantId: 1,
      name: newRole.name,
      description: newRole.description,
      permissions: newRole.permissions,
      userCount: 0,
      createdAt: new Date().toISOString(),
    };
    setRoles(prev => [...prev, role]);
    setNewRole({ name: "", description: "", permissions: [] });
    setShowCreate(false);
  };

  const handleDelete = (roleId: number) => {
    setRoles(prev => prev.filter(r => r.id !== roleId));
  };

  const permLabel = (key: string) => ALL_PERMISSIONS.find(p => p.key === key)?.label ?? key;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Roles & Permissions</h1>
          <p className="text-sm text-muted-foreground mt-1">{roles.length} roles configured</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-role"
        >
          <Plus className="w-4 h-4" /> New Role
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
        {roles.map((role, i) => (
          <motion.div
            key={role.id}
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: i * 0.08 }}
            className="bg-card border border-card-border rounded-xl p-5 shadow-sm"
            data-testid={`card-role-${role.id}`}
          >
            <div className="flex items-start justify-between mb-3">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-blue-50 text-blue-600 rounded-lg">
                  <Shield className="w-4 h-4" />
                </div>
                <div>
                  <h3 className="font-semibold text-foreground">{role.name}</h3>
                  <p className="text-xs text-muted-foreground flex items-center gap-1 mt-0.5">
                    <Users className="w-3 h-3" />{role.userCount} users
                  </p>
                </div>
              </div>
              <button onClick={() => handleDelete(role.id)} className="p-1.5 text-muted-foreground hover:text-rose-500 hover:bg-rose-50 rounded-lg transition">
                <Trash2 className="w-3.5 h-3.5" />
              </button>
            </div>

            {role.description && (
              <p className="text-xs text-muted-foreground mb-3 leading-relaxed">{role.description}</p>
            )}

            <div className="flex flex-wrap gap-1.5">
              {role.permissions.map(perm => (
                <span key={perm} className="inline-flex px-2 py-0.5 bg-blue-50 text-blue-700 text-xs font-medium rounded-md border border-blue-100">
                  {permLabel(perm)}
                </span>
              ))}
              {role.permissions.length === 0 && (
                <span className="text-xs text-muted-foreground">No permissions assigned</span>
              )}
            </div>
          </motion.div>
        ))}
      </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 Role</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">Role Name *</label>
                  <input value={newRole.name} onChange={e => setNewRole(p => ({ ...p, name: e.target.value }))}
                    placeholder="e.g. Developer"
                    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">Description</label>
                  <input value={newRole.description} onChange={e => setNewRole(p => ({ ...p, description: e.target.value }))}
                    placeholder="Optional description..."
                    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-2 block">Permissions</label>
                  <div className="grid grid-cols-2 gap-2">
                    {ALL_PERMISSIONS.map(p => (
                      <label key={p.key} className="flex items-center gap-2 cursor-pointer">
                        <input
                          type="checkbox"
                          checked={newRole.permissions.includes(p.key)}
                          onChange={() => togglePermission(p.key)}
                          className="w-3.5 h-3.5 rounded border-gray-300 text-primary focus:ring-primary/30"
                        />
                        <span className="text-xs text-foreground">{p.label}</span>
                      </label>
                    ))}
                  </div>
                </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 Role</button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
