import React, { useState, useMemo, useEffect } from "react";
import Topbar from "../../../shared/components/Topbar";
import { useLiveRows } from "../../../shared/hooks/useLiveRows";
import { PageLoading } from "../../../shared/components/PageLoading";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  CartesianGrid,
} from "recharts";
import {
  ShieldCheck,
  Search,
  Plus,
  Info,
  Check,
  X as XIcon,
  History,
  UserCog,
  PieChart as PieIcon,
} from "lucide-react";

const emptyPermissions = (modules) =>
  Object.fromEntries(modules.map((m) => [m, { view: true, edit: false, manage: false }]));

const MODULES = [
  "Devices",
  "Hardware",
  "Firmware",
  "Event Engine",
  "Automation",
  "Hardware Merge",
  "Power Management",
  "Diagnostics",
  "Logs",
  "Analytics",
  "Reports",
  "Settings",
];

const auditLog = [
  { text: "Field Engineer granted Edit on Diagnostics", who: "A. Verma", time: "18 min ago" },
  { text: "Viewer role created", who: "System", time: "2 hours ago" },
  { text: "Super Admin — Manage revoked on Reports (reverted)", who: "A. Verma", time: "5 hours ago" },
  { text: "Field Engineer added to 2 new users", who: "S. Iyer", time: "Yesterday" },
  { text: "Permissions matrix reviewed for compliance", who: "System", time: "2 days ago" },
];

export default function Permissions({ onMenuClick }) {
  const { rows: roleRows, loading: rolesLoading, add: addRole, update: updateRole } = useLiveRows("roles");
  const { rows: permRows, loading: permsLoading } = useLiveRows("permissions");

  const roles = useMemo(() => {
    return roleRows.map((r) => {
      const permDoc = permRows.find((p) => p.roleId === r.id || p.role === r.name);
      return {
        ...r,
        color: r.color || "bg-gray-300",
        users: r.users ?? 0,
        description: r.description || "No description provided.",
        permissions: permDoc?.permissions || r.permissions || emptyPermissions(MODULES),
      };
    });
  }, [roleRows, permRows]);

  const [activeRole, setActiveRole] = useState(null);
  useEffect(() => {
    if (roles.length && !activeRole) setActiveRole(roles[0].id);
    if (roles.length && activeRole && !roles.find((r) => r.id === activeRole)) {
      setActiveRole(roles[0].id);
    }
  }, [roles, activeRole]);

  const [search, setSearch] = useState("");

  const [newRoleModalOpen, setNewRoleModalOpen] = useState(false);
  const [newRoleName, setNewRoleName] = useState("");
  const [newRoleDesc, setNewRoleDesc] = useState("");
  const [newRoleError, setNewRoleError] = useState("");

  const [toastMessage, setToastMessage] = useState("");
  const showToast = (msg) => {
    setToastMessage(msg);
    setTimeout(() => setToastMessage(""), 2200);
  };

  const handleCreateRole = async () => {
    if (!newRoleName.trim()) {
      setNewRoleError("Role name is required");
      return;
    }
    const name = newRoleName.trim();
    const id = await addRole({
      name,
      users: 0,
      color: "bg-gray-300",
      description: newRoleDesc.trim() || "No description provided.",
      permissions: emptyPermissions(MODULES),
    });
    setActiveRole(id);
    setNewRoleName("");
    setNewRoleDesc("");
    setNewRoleError("");
    setNewRoleModalOpen(false);
    showToast(`${name} role created`);
  };

  const current = roles.find((r) => r.id === activeRole) || roles[0];

  const togglePermission = async (moduleName, key) => {
    if (!current || current.name === "Super Admin") return;
    const nextPerms = {
      ...current.permissions,
      [moduleName]: {
        ...current.permissions[moduleName],
        [key]: !current.permissions[moduleName][key],
      },
    };
    await updateRole(current.id, { ...current, permissions: nextPerms });
  };

  const filteredModules = MODULES.filter((m) =>
    m.toLowerCase().includes(search.toLowerCase())
  );

  const coverageData = roles.map((r) => {
    const total = MODULES.length * 3;
    const granted = MODULES.reduce((sum, m) => {
      const p = r.permissions[m];
      return sum + (p.view ? 1 : 0) + (p.edit ? 1 : 0) + (p.manage ? 1 : 0);
    }, 0);
    return { name: r.name, coverage: Math.round((granted / total) * 100) };
  });

  if (rolesLoading || permsLoading) return <PageLoading label="Loading permissions…" />;
  if (!current) return <PageLoading label="No roles configured" />;

  return (
    <div className="min-h-screen bg-gray-50">
      <Topbar onMenuClick={onMenuClick} />

      <div className="max-w-[1600px] mx-auto px-8 py-8">
        {toastMessage && (
          <div className="fixed top-6 right-6 z-50 flex items-center gap-2 bg-white border border-gray-200 shadow-lg rounded-lg px-4 py-3">
            <div className="w-5 h-5 rounded-full bg-red-600 flex items-center justify-center">
              <Check className="w-3 h-3 text-white" />
            </div>
            <span className="text-sm text-gray-900">{toastMessage}</span>
          </div>
        )}

        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
          <div>
            <h1 className="text-xl font-semibold text-gray-900">Permissions</h1>
            <p className="text-sm text-gray-500 mt-1">
              Control what each role can view, edit, and manage
            </p>
          </div>
          <button
            onClick={() => setNewRoleModalOpen(true)}
            className="flex items-center justify-center gap-1.5 bg-red-600 hover:bg-red-500 text-white text-sm font-medium px-3.5 py-2 rounded-lg transition-colors"
          >
            <Plus className="w-3.5 h-3.5" />
            New role
          </button>
        </div>

        <div className="grid grid-cols-1 xl:grid-cols-5 gap-6">
          {/* Roles list + coverage chart */}
          <div className="xl:col-span-1 flex flex-col gap-6">
            <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
              <div className="px-4 py-3 border-b border-gray-200">
                <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
                  Roles
                </h2>
              </div>
              <div>
                {roles.map((r) => (
                  <button
                    key={r.id}
                    onClick={() => setActiveRole(r.id)}
                    className={`w-full flex items-center justify-between px-4 py-3 text-left border-l-2 transition-colors ${
                      activeRole === r.id
                        ? "border-red-600 bg-red-50"
                        : "border-transparent hover:bg-gray-100"
                    }`}
                  >
                    <div className="flex items-center gap-2.5">
                      <span className={`w-2 h-2 rounded-full ${r.color}`} />
                      <span
                        className={`text-sm font-medium ${
                          activeRole === r.id ? "text-red-600" : "text-gray-900"
                        }`}
                      >
                        {r.name}
                      </span>
                    </div>
                    <span className="text-xs text-gray-400">{r.users} users</span>
                  </button>
                ))}
              </div>
            </div>

            <div className="flex items-start gap-2 bg-white border border-gray-200 rounded-xl p-3.5">
              <Info className="w-3.5 h-3.5 text-gray-400 mt-0.5 shrink-0" />
              <p className="text-xs text-gray-500 leading-relaxed">
                Manage permission implies edit + delete + assign access for that module.
              </p>
            </div>

            {/* Coverage chart - fills remaining left column height */}
            <div className="bg-white border border-gray-200 rounded-xl p-4 flex-1 flex flex-col">
              <div className="flex items-center gap-2 mb-4">
                <PieIcon className="w-4 h-4 text-red-600" />
                <h2 className="text-sm font-semibold text-gray-900">Permission coverage</h2>
              </div>
              <div className="flex-1 min-h-[180px]">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={coverageData} layout="vertical" margin={{ left: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#E5E7EB" horizontal={false} />
                    <XAxis type="number" domain={[0, 100]} tick={{ fontSize: 11, fill: "#6B7280" }} />
                    <YAxis
                      type="category"
                      dataKey="name"
                      width={90}
                      tick={{ fontSize: 11, fill: "#111827" }}
                    />
                    <Tooltip
                      formatter={(v) => [`${v}%`, "Coverage"]}
                      contentStyle={{ fontSize: 12, borderRadius: 8, borderColor: "#E5E7EB" }}
                    />
                    <Bar dataKey="coverage" fill="#dc2626" radius={[0, 4, 4, 0]} barSize={18} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>
          </div>

          {/* Permission matrix */}
          <div className="xl:col-span-3">
            <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
              <div className="flex items-center justify-between px-5 py-4 border-b border-gray-200">
                <div className="flex items-center gap-2">
                  <ShieldCheck className="w-4 h-4 text-red-600" />
                  <h2 className="text-sm font-semibold text-gray-900">
                    {current.name} — module permissions
                  </h2>
                </div>
                <div className="relative">
                  <Search className="w-3.5 h-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
                  <input
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder="Search modules"
                    className="pl-8 pr-3 py-1.5 text-sm rounded-lg border border-gray-200 outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500 w-48"
                  />
                </div>
              </div>

              <div className="overflow-x-auto">
              <table className="w-full text-sm min-w-[480px]">
                <thead>
                  <tr className="text-left text-gray-500 border-b border-gray-200">
                    <th className="px-5 py-3 font-medium">Module</th>
                    <th className="px-5 py-3 font-medium text-center">View</th>
                    <th className="px-5 py-3 font-medium text-center">Edit</th>
                    <th className="px-5 py-3 font-medium text-center">Manage</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredModules.map((m) => {
                    const perm = current.permissions[m];
                    return (
                      <tr
                        key={m}
                        className="border-b border-gray-200 last:border-0 hover:bg-gray-100 transition-colors"
                      >
                        <td className="px-5 py-3 text-gray-900 font-medium">{m}</td>
                        {["view", "edit", "manage"].map((key) => (
                          <td key={key} className="px-5 py-3 text-center">
                            <button
                              onClick={() => togglePermission(m, key)}
                              disabled={current.name === "Super Admin"}
                              className={`w-6 h-6 rounded-md inline-flex items-center justify-center border transition-colors disabled:cursor-not-allowed ${
                                perm[key]
                                  ? "bg-red-600 border-red-600 text-white"
                                  : "bg-white border-gray-200 text-gray-300 hover:border-gray-300"
                              }`}
                            >
                              {perm[key] ? <Check className="w-3.5 h-3.5" /> : <XIcon className="w-3.5 h-3.5" />}
                            </button>
                          </td>
                        ))}
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              </div>
            </div>
          </div>

          {/* Role details + audit log */}
          <div className="xl:col-span-1 flex flex-col gap-6">
            <div className="bg-white border border-gray-200 rounded-xl p-5">
              <div className="flex items-center gap-2 mb-4">
                <UserCog className="w-4 h-4 text-red-600" />
                <h2 className="text-sm font-semibold text-gray-900">Role details</h2>
              </div>
              <p className="text-sm font-medium text-gray-900">{current.name}</p>
              <p className="text-xs text-gray-500 mt-1.5 leading-relaxed">{current.description}</p>
              <div className="mt-4 pt-4 border-t border-gray-200 flex items-center justify-between">
                <span className="text-xs text-gray-500">Assigned users</span>
                <span className="text-sm font-semibold text-gray-900">{current.users}</span>
              </div>
            </div>

            <div className="bg-white border border-gray-200 rounded-xl overflow-hidden flex-1">
              <div className="px-5 py-4 border-b border-gray-200 flex items-center gap-2">
                <History className="w-4 h-4 text-red-600" />
                <h2 className="text-sm font-semibold text-gray-900">Audit log</h2>
              </div>
              <div className="divide-y divide-gray-200">
                {auditLog.map((a, i) => (
                  <div key={i} className="px-5 py-3.5">
                    <p className="text-sm text-gray-900 leading-snug">{a.text}</p>
                    <p className="text-xs text-gray-400 mt-1">
                      {a.who} · {a.time}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      {newRoleModalOpen && (
        <div className="fixed inset-0 bg-gray-900/40 flex items-center justify-center z-50 px-4">
          <div className="bg-white rounded-xl border border-gray-200 shadow-xl w-full max-w-sm p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-semibold text-gray-900">New role</h3>
              <button
                onClick={() => setNewRoleModalOpen(false)}
                className="text-gray-400 hover:text-gray-600"
              >
                <XIcon className="w-4 h-4" />
              </button>
            </div>

            <label className="block text-sm font-medium text-gray-900 mb-1.5">
              Role name
            </label>
            <input
              value={newRoleName}
              onChange={(e) => setNewRoleName(e.target.value)}
              placeholder="e.g. Regional Manager"
              className={`w-full px-3 py-2.5 rounded-lg border text-sm outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500 mb-1 ${
                newRoleError ? "border-red-400" : "border-gray-200"
              }`}
            />
            {newRoleError && (
              <p className="text-xs text-red-600 mb-3">{newRoleError}</p>
            )}

            <label className="block text-sm font-medium text-gray-900 mb-1.5 mt-4">
              Description
            </label>
            <textarea
              value={newRoleDesc}
              onChange={(e) => setNewRoleDesc(e.target.value)}
              placeholder="What can this role do?"
              rows={3}
              className="w-full px-3 py-2.5 rounded-lg border border-gray-200 text-sm outline-none focus:ring-2 focus:ring-red-100 focus:border-red-500 mb-5 resize-none"
            />

            <div className="flex justify-end gap-2">
              <button
                onClick={() => setNewRoleModalOpen(false)}
                className="text-sm font-medium text-gray-600 hover:text-gray-900 px-3 py-2"
              >
                Cancel
              </button>
              <button
                onClick={handleCreateRole}
                className="bg-red-600 hover:bg-red-500 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
              >
                Create role
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}