"use client";

import * as React from "react";
import { toast } from "sonner";
import {
  Shield,
  Plus,
  Trash2,
  Edit2,
  Users,
  Copy,
  CheckCircle2,
  Lock,
  Sparkles,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { FloatingInput, FloatingTextarea } from "@/components/ui/floating-input";
import { Checkbox } from "@/components/ui/checkbox";
import { fetchWithAdminCache, invalidateAdminCache } from "@/lib/admin/client-cache";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

interface RoleItem {
  id: string;
  name: string;
  description: string;
  permissions: string[];
  isSystem?: boolean;
  assignedCount: number;
}

const PERMISSION_GROUPS = [
  {
    group: "Blog & Content Operations",
    permissions: [
      { id: "posts.create", label: "Create Articles", desc: "Draft new articles in the publishing studio" },
      { id: "posts.edit", label: "Edit Articles", desc: "Modify draft and existing blog content" },
      { id: "posts.publish", label: "Publish & Schedule", desc: "Push articles live or schedule future releases" },
      { id: "content.view_activity", label: "View Editorial Activity", desc: "Inspect recent publishing and revisions audit log" },
    ],
  },
  {
    group: "Media & Assets",
    permissions: [
      { id: "media.manage", label: "Manage Media Library", desc: "Upload, curate, and optimize brand media assets" },
    ],
  },
  {
    group: "SEO & Traffic Routing",
    permissions: [
      { id: "seo.manage", label: "SEO & Social Metadata", desc: "Configure title tags, schema, robots, and OpenGraph" },
      { id: "redirects.manage", label: "Manage URL Redirects", desc: "Create and modify 301, 302, 307, 308 redirect rules" },
    ],
  },
  {
    group: "Administration & User Governance",
    permissions: [
      { id: "admin.manage", label: "Manage Administrators", desc: "Provision new sub-admins and suspend accounts" },
      { id: "roles.manage", label: "Manage Roles & RBAC", desc: "Create, edit, and duplicate custom administrator roles" },
      { id: "admin.force_logout", label: "Force Logout Sessions", desc: "Revoke active administrator sessions instantly" },
      { id: "admin.reset_password", label: "Reset Admin Passwords", desc: "Directly trigger password resets for other administrators" },
    ],
  },
  {
    group: "Security & Auditing",
    permissions: [
      { id: "security.view_audit", label: "View Security Audit Log", desc: "Inspect login telemetry, IPs, and session events" },
      { id: "security.manage_reset_requests", label: "Handle Reset Requests", desc: "Approve or reject sub-admin password recovery tickets" },
      { id: "security.manage_settings", label: "Configure Security Settings", desc: "Set session timeouts and global 2FA policies" },
    ],
  },
];

export function RolesPanel() {
  const [roles, setRoles] = React.useState<RoleItem[]>([]);
  const [loading, setLoading] = React.useState(true);

  // Create / Edit Modal State
  const [modalOpen, setModalOpen] = React.useState(false);
  const [editingRoleId, setEditingRoleId] = React.useState<string | null>(null);
  const [roleName, setRoleName] = React.useState("");
  const [roleDesc, setRoleDesc] = React.useState("");
  const [selectedPermissions, setSelectedPermissions] = React.useState<string[]>([]);
  const [saving, setSaving] = React.useState(false);

  // Delete Alert State
  const [toDelete, setToDelete] = React.useState<RoleItem | null>(null);
  const [deleting, setDeleting] = React.useState(false);

  const fetchRoles = async (forceFresh = false) => {
    try {
      setLoading(true);
      const data = await fetchWithAdminCache<{ roles?: RoleItem[] }>("/api/admin/roles", {
        tags: ["roles"],
        forceFresh,
      });
      setRoles(data.roles || []);
    } catch (err: any) {
      toast.error(err.message || "Failed to load roles");
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchRoles();
  }, []);

  const openCreateModal = () => {
    setEditingRoleId(null);
    setRoleName("");
    setRoleDesc("");
    setSelectedPermissions(["posts.create", "posts.edit"]);
    setModalOpen(true);
  };

  const openEditModal = (role: RoleItem) => {
    if (role.isSystem) return;
    setEditingRoleId(role.id);
    setRoleName(role.name);
    setRoleDesc(role.description || "");
    setSelectedPermissions([...role.permissions]);
    setModalOpen(true);
  };

  const handleDuplicate = (role: RoleItem) => {
    setEditingRoleId(null);
    setRoleName(`${role.name} (Copy)`);
    setRoleDesc(role.description || "");
    setSelectedPermissions([...role.permissions]);
    setModalOpen(true);
  };

  const togglePermission = (permId: string) => {
    setSelectedPermissions((prev) =>
      prev.includes(permId) ? prev.filter((p) => p !== permId) : [...prev, permId]
    );
  };

  const handleSaveRole = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!roleName.trim()) {
      toast.error("Role name is required.");
      return;
    }

    try {
      setSaving(true);
      const url = editingRoleId ? `/api/admin/roles/${editingRoleId}` : "/api/admin/roles";
      const method = editingRoleId ? "PATCH" : "POST";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: roleName.trim(),
          description: roleDesc.trim(),
          permissions: selectedPermissions,
        }),
      });

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Save failed.");

      toast.success(editingRoleId ? "Role updated successfully!" : "Custom role created!");
      setModalOpen(false);
      invalidateAdminCache("roles");
      fetchRoles(true);
    } catch (err: any) {
      toast.error(err.message || "Failed to save role.");
    } finally {
      setSaving(false);
    }
  };

  const handleDeleteRole = async () => {
    if (!toDelete) return;
    try {
      setDeleting(true);
      const res = await fetch(`/api/admin/roles/${toDelete.id}`, { method: "DELETE" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to delete role.");

      toast.success("Role deleted successfully!");
      setToDelete(null);
      invalidateAdminCache("roles");
      fetchRoles(true);
    } catch (err: any) {
      toast.error(err.message || "Deletion failed.");
    } finally {
      setDeleting(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="font-bold text-xl tracking-tight text-neutral-900 dark:text-white">
            Custom Administrator Roles & Permissions
          </h1>
          <p className="mt-0.5 text-xs text-neutral-500">
            Define granular capabilities for sub-administrators, editors, and SEO managers with real server-side enforcement.
          </p>
        </div>

        <Button
          onClick={openCreateModal}
          className="gap-1.5 rounded-xl text-xs font-semibold"
        >
          <Plus className="h-4 w-4" />
          <span>Create Custom Role</span>
        </Button>
      </div>

      {/* Roles Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {loading ? (
          <div className="col-span-2 py-16 text-center text-xs text-neutral-400">
            Loading roles and permission matrix...
          </div>
        ) : (
          roles.map((role) => {
            const isMainAdmin = role.id === "MAIN_ADMIN";
            return (
              <div
                key={role.id}
                className="rounded-2xl border border-neutral-200 bg-white p-5 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 flex flex-col justify-between space-y-4"
              >
                <div>
                  <div className="flex items-start justify-between gap-2">
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                          {role.name}
                        </h3>
                        {role.isSystem ? (
                          <Badge variant="outline" className="text-[10px] bg-neutral-100 dark:bg-neutral-800 font-mono">
                            <Lock className="h-2.5 w-2.5 mr-1 text-neutral-500" />
                            System
                          </Badge>
                        ) : (
                          <Badge className="bg-emerald-50 text-emerald-700 border-emerald-200 text-[10px] font-mono">
                            <Sparkles className="h-2.5 w-2.5 mr-1" />
                            Custom
                          </Badge>
                        )}
                      </div>
                      <p className="text-xs text-neutral-500 mt-1 leading-relaxed">
                        {role.description}
                      </p>
                    </div>

                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDuplicate(role)}
                        className="h-7 w-7 p-0 text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
                        title="Duplicate Role"
                      >
                        <Copy className="h-3.5 w-3.5" />
                      </Button>

                      {!role.isSystem && (
                        <>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => openEditModal(role)}
                            className="h-7 w-7 p-0 text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
                            title="Edit Role"
                          >
                            <Edit2 className="h-3.5 w-3.5" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => setToDelete(role)}
                            className="h-7 w-7 p-0 text-red-500 hover:text-red-600"
                            title="Delete Role"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </Button>
                        </>
                      )}
                    </div>
                  </div>

                  {/* Permissions Summary Badges */}
                  <div className="mt-4 flex flex-wrap gap-1.5">
                    {isMainAdmin ? (
                      <span className="rounded-md bg-neutral-900 text-white px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider dark:bg-white dark:text-neutral-900">
                        Unrestricted Full Access (All Capabilities)
                      </span>
                    ) : role.permissions.length === 0 ? (
                      <span className="text-[11px] text-neutral-400 italic">No permissions assigned</span>
                    ) : (
                      role.permissions.map((p) => (
                        <span
                          key={p}
                          className="rounded-md bg-neutral-100 text-neutral-700 px-2 py-0.5 text-[10px] font-mono dark:bg-neutral-800 dark:text-neutral-300"
                        >
                          {p}
                        </span>
                      ))
                    )}
                  </div>
                </div>

                {/* Footer Meta */}
                <div className="flex items-center justify-between border-t border-neutral-100 pt-3 text-[11px] text-neutral-400 dark:border-neutral-800">
                  <div className="flex items-center gap-1.5">
                    <Users className="h-3.5 w-3.5 text-neutral-500" />
                    <span>
                      {role.assignedCount} {role.assignedCount === 1 ? "Admin Assigned" : "Admins Assigned"}
                    </span>
                  </div>
                  <span>{role.permissions.length} Permissions</span>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* CREATE / EDIT ROLE MODAL */}
      <Dialog open={modalOpen} onOpenChange={setModalOpen}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <form onSubmit={handleSaveRole}>
            <DialogHeader>
              <DialogTitle>
                {editingRoleId ? "Edit Custom Role" : "Create Custom Role"}
              </DialogTitle>
              <DialogDescription>
                Select granular privileges for this role. Only allowed features will be available in the admin UI and authorized on backend APIs.
              </DialogDescription>
            </DialogHeader>

            <div className="space-y-4 py-4">
              <FloatingInput
                id="role-name"
                label="Role Title *"
                placeholder="e.g. Senior SEO Strategist"
                required
                value={roleName}
                onChange={(e) => setRoleName(e.target.value)}
              />

              <FloatingTextarea
                id="role-description"
                label="Description of Duties"
                placeholder="Brief summary of what team members in this role are responsible for..."
                rows={2}
                value={roleDesc}
                onChange={(e) => setRoleDesc(e.target.value)}
              />

              <div className="border-t border-neutral-200 dark:border-neutral-800 pt-3">
                <h4 className="text-xs font-bold text-neutral-900 dark:text-white uppercase tracking-wider mb-3">
                  Granular Permission Matrix
                </h4>

                <div className="space-y-5">
                  {PERMISSION_GROUPS.map((grp) => (
                    <div key={grp.group} className="space-y-2">
                      <span className="text-[11px] font-bold text-neutral-500 uppercase">
                        {grp.group}
                      </span>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                        {grp.permissions.map((perm) => {
                          const isChecked = selectedPermissions.includes(perm.id);
                          return (
                            <div
                              key={perm.id}
                              onClick={() => togglePermission(perm.id)}
                              className={`flex items-start gap-2.5 p-2.5 rounded-xl border cursor-pointer transition ${
                                isChecked
                                  ? "border-neutral-900 bg-neutral-50 dark:border-white dark:bg-neutral-800/60"
                                  : "border-neutral-200 hover:border-neutral-300 dark:border-neutral-800"
                              }`}
                            >
                              <Checkbox
                                checked={isChecked}
                                onCheckedChange={() => togglePermission(perm.id)}
                                className="mt-0.5"
                              />
                              <div className="text-xs leading-tight select-none">
                                <div className="font-semibold text-neutral-900 dark:text-white">
                                  {perm.label}
                                </div>
                                <div className="text-[10px] text-neutral-400 mt-0.5">
                                  {perm.desc}
                                </div>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            <DialogFooter className="gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => setModalOpen(false)}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={saving || !roleName.trim()}
              >
                {saving ? "Saving..." : editingRoleId ? "Update Role" : "Create Role"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* DELETE CONFIRMATION DIALOG */}
      <AlertDialog open={!!toDelete} onOpenChange={() => setToDelete(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Custom Role?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete{" "}
              <strong className="text-neutral-900 dark:text-white">{toDelete?.name}</strong>?
              {toDelete && toDelete.assignedCount > 0 && (
                // block-display <span> (not <div>) — valid inside the
                // AlertDialogDescription <p>; a <div> here causes a hydration error.
                <span className="mt-2 block text-red-600 font-semibold">
                  Warning: {toDelete.assignedCount} administrator(s) are assigned to this role. You must reassign them to another role before deleting.
                </span>
              )}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDeleteRole}
              disabled={deleting || (toDelete ? toDelete.assignedCount > 0 : false)}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              {deleting ? "Deleting..." : "Delete Role"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

export default RolesPanel;
