import { useState, useEffect } from "react";
import { Plus, Trash2, Pencil, RefreshCcw, AlertCircle, Loader2 } from "lucide-react";
import MaterialTable from "@material-table/core";
import { getAllRoles, createRole, updateRole, deleteRole, type Role } from "../api/roles";
import ConfirmModal from "../components/layout/common/ConfirmModal";

interface RoleForm {
  name: string;
  description: string;
  permissions?: Record<string, Record<string, boolean>>;
}

export default function RolesPage() {
  const [roles, setRoles] = useState<Role[]>([]);
  const [activeRole, setActiveRole] = useState<Role | null>(null);
  const [search, setSearch] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [showModal, setShowModal] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);

  const emptyForm: RoleForm = {
    name: "",
    description: "",
    permissions: {},
  };

  const [form, setForm] = useState<RoleForm>(emptyForm);

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

  const fetchRoles = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getAllRoles();
      setRoles(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load roles");
      console.error("Error fetching roles:", err);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (!form.name.trim()) {
      setError("Role name is required");
      return;
    }

    setLoading(true);
    setError(null);
    try {
      if (editingId) {
        const updated = await updateRole(editingId, form);
        setRoles(prev => prev.map(r => r.id === editingId ? updated : r));
      } else {
        const created = await createRole(form);
        setRoles(prev => [...prev, created]);
      }
      setShowModal(false);
      setEditingId(null);
      setForm(emptyForm);
      setActiveRole(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save role");
      console.error("Error saving role:", err);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!activeRole) return;

    setLoading(true);
    setError(null);
    try {
      await deleteRole(activeRole.id);
      setRoles(prev => prev.filter(r => r.id !== activeRole.id));
      setActiveRole(null);
      setShowDeleteConfirm(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to delete role");
      console.error("Error deleting role:", err);
    } finally {
      setLoading(false);
    }
  };

  const openEditModal = () => {
    if (!activeRole) return;
    setEditingId(activeRole.id);
    setForm({
      name: activeRole.name,
      description: activeRole.description,
      permissions: activeRole.permissions,
    });
    setShowModal(true);
  };

  const filtered = roles.filter(r => 
    r.name.toLowerCase().includes(search.toLowerCase()) ||
    r.description?.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="flex gap-6 p-6 w-full bg-gray-100">
      {/* LEFT INFO SIDEBAR */}
      <div className="w-72 bg-white rounded-xl shadow p-4">
        <h3 className="text-xs font-semibold text-gray-500 mb-3">Role Information</h3>
        <p className="text-sm text-gray-700 mb-4">
          Manage system roles and their permissions. Roles define what actions users can perform.
        </p>
        
        {activeRole && (
          <div className="mt-6 pt-4 border-t">
            <h4 className="text-xs font-semibold text-gray-500 mb-2">Selected Role</h4>
            <div className="space-y-2">
              <div>
                <p className="text-xs text-gray-500">Name</p>
                <p className="text-sm font-medium">{activeRole.name}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500">Description</p>
                <p className="text-sm">{activeRole.description || "No description"}</p>
              </div>
              <div>
                <p className="text-xs text-gray-500">Created</p>
                <p className="text-sm">{new Date(activeRole.created_at).toLocaleDateString()}</p>
              </div>
              {activeRole.permissions && Object.keys(activeRole.permissions).length > 0 && (
                <div>
                  <p className="text-xs text-gray-500">Permissions</p>
                  <p className="text-sm">{Object.keys(activeRole.permissions).length} permission groups</p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* MAIN */}
      <div className="flex-1 flex flex-col gap-6">
        {/* HEADER */}
        <div className="rounded-xl shadow p-6 text-white flex justify-between items-center"
             style={{ background: "linear-gradient(135deg, #4c5f9e, #2a355d, #566bb8)" }}>
          <div>
            <h1 className="text-2xl font-bold">Role Management</h1>
            <p className="text-sm text-blue-100">{roles.length} roles registered</p>
          </div>
          <div className="flex gap-3">
            <button 
              onClick={() => { setForm(emptyForm); setEditingId(null); setShowModal(true); }}
              disabled={loading}
              className="flex items-center gap-2 px-4 py-2 bg-white text-[#4c5f9e] rounded-lg hover:bg-gray-100 transition disabled:opacity-50"
            >
              <Plus size={16} /> Add
            </button>
            <button 
              onClick={openEditModal}
              disabled={!activeRole || loading}
              className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg hover:bg-white/10 transition disabled:opacity-50"
            >
              <Pencil size={16} /> Edit
            </button>
            <button 
              onClick={() => setShowDeleteConfirm(true)}
              disabled={!activeRole || loading}
              className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg hover:bg-red-500/20 transition disabled:opacity-50"
            >
              <Trash2 size={16} /> Delete
            </button>
            <button 
              onClick={fetchRoles}
              disabled={loading}
              className="flex items-center gap-2 px-4 py-2 border border-white/40 rounded-lg hover:bg-white/10 transition disabled:opacity-50"
            >
              {loading ? <Loader2 size={16} className="animate-spin" /> : <RefreshCcw size={16} />} 
              Refresh
            </button>
          </div>
        </div>

        {/* ERROR ALERT */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center gap-3">
            <AlertCircle className="text-red-600" size={20} />
            <div>
              <p className="text-sm font-medium text-red-800">Error</p>
              <p className="text-sm text-red-600">{error}</p>
            </div>
            <button 
              onClick={() => setError(null)}
              className="ml-auto text-red-600 hover:text-red-800"
            >
              ×
            </button>
          </div>
        )}

        {/* SEARCH */}
        <input 
          className="bg-white rounded-lg shadow px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          placeholder="Search role by name or description..."
          value={search}
          onChange={e => setSearch(e.target.value)} 
        />

        {/* TABLE */}
        <div className="bg-white rounded-xl shadow">
          {loading && roles.length === 0 ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="animate-spin text-blue-600" size={32} />
            </div>
          ) : (
            <MaterialTable
              title="Roles"
              columns={[
                { 
                  title: "Name", 
                  field: "name",
                  render: (rowData) => (
                    <span className="font-medium text-gray-900">{rowData.name}</span>
                  )
                },
                { 
                  title: "Description", 
                  field: "description",
                  render: (rowData) => (
                    <span className="text-gray-600">{rowData.description || "—"}</span>
                  )
                },
                {
                  title: "Permissions",
                  field: "permissions",
                  render: (rowData) => {
                    const count = rowData.permissions ? Object.keys(rowData.permissions).length : 0;
                    return (
                      <span className="text-sm text-gray-600">
                        {count > 0 ? `${count} groups` : "No permissions"}
                      </span>
                    );
                  }
                },
                { 
                  title: "Created", 
                  field: "created_at", 
                  type: "date",
                  render: (rowData) => (
                    <span className="text-sm text-gray-600">
                      {new Date(rowData.created_at).toLocaleDateString()}
                    </span>
                  )
                }
              ]}
              data={filtered}
              onRowClick={(_, rowData) => setActiveRole(rowData as Role)}
              options={{
                actionsColumnIndex: -1,
                search: false,
                paging: true,
                pageSize: 10,
                pageSizeOptions: [10, 20, 50],
                sorting: true,
                rowStyle: (rowData) => ({ 
                  backgroundColor: activeRole?.id === (rowData as Role).id ? "#EEF2FF" : "#FFFFFF",
                  cursor: "pointer"
                })
              }}
            />
          )}
        </div>
      </div>

      {/* ADD/EDIT MODAL */}
      {showModal && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 w-96 space-y-4 shadow-xl">
            <h2 className="text-lg font-semibold text-gray-900">
              {editingId ? "Edit Role" : "Add New Role"}
            </h2>
            
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Name <span className="text-red-500">*</span>
                </label>
                <input 
                  className="w-full border border-gray-300 px-3 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" 
                  placeholder="e.g., ADMIN, USER, MANAGER" 
                  value={form.name} 
                  onChange={e => setForm({...form, name: e.target.value})}
                  disabled={loading}
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Description
                </label>
                <textarea 
                  className="w-full border border-gray-300 px-3 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none" 
                  placeholder="Describe the role's purpose..." 
                  rows={3}
                  value={form.description} 
                  onChange={e => setForm({...form, description: e.target.value})}
                  disabled={loading}
                />
              </div>

              {/* Note about permissions */}
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
                <p className="text-xs text-blue-800">
                  <strong>Note:</strong> Permissions can be configured after creating the role.
                </p>
              </div>
            </div>

            <div className="flex justify-end gap-2 pt-3 border-t">
              <button 
                onClick={() => {
                  setShowModal(false);
                  setEditingId(null);
                  setForm(emptyForm);
                  setError(null);
                }}
                disabled={loading}
                className="px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg transition disabled:opacity-50"
              >
                Cancel
              </button>
              <button 
                onClick={handleSave} 
                disabled={loading || !form.name.trim()}
                className="bg-[#4c5f9e] text-white px-4 py-2 rounded-lg hover:bg-[#3d4c7d] transition disabled:opacity-50 flex items-center gap-2"
              >
                {loading && <Loader2 size={16} className="animate-spin" />}
                {loading ? "Saving..." : "Save"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* DELETE CONFIRMATION MODAL */}
      <ConfirmModal
        open={showDeleteConfirm}
        onClose={() => setShowDeleteConfirm(false)}
        onConfirm={handleDelete}
        title="Delete Role"
        message={`Are you sure you want to delete the role "${activeRole?.name}"? This action cannot be undone.`}
        confirmText="Delete"
        danger={true}
        loading={loading}
      />
    </div>
  );
}
