"use client";

import { CheckCircle2, Edit2, Loader2, Lock, Plus, RefreshCw, Save, Shield, Trash2, X } from "lucide-react";
import { useEffect, useState } from "react";
import { ALL_SYSTEM_MODULES, DEFAULT_SYSTEM_ROLES } from "@/services/settings-service";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { ModulePermission, RoleGroup } from "@/types/settings";

interface RolesPermissionsTabProps {
  roles: RoleGroup[];
  onCreateRole: (data: { name: string; description: string; permissions: ModulePermission[] }) => Promise<any>;
  onUpdateRole?: (id: string, data: Partial<RoleGroup>) => Promise<any>;
  onDeleteRole?: (id: string) => Promise<any>;
  onResetRoles?: () => Promise<any>;
  isSaving?: boolean;
}

export function RolesPermissionsTab({
  roles,
  onCreateRole,
  onUpdateRole,
  onDeleteRole,
  onResetRoles,
  isSaving = false,
}: RolesPermissionsTabProps) {
  const allRoles = roles.length > 0 ? roles : DEFAULT_SYSTEM_ROLES;

  const [selectedRoleId, setSelectedRoleId] = useState<string>(allRoles[0]?.id || "role-admin");
  const [rolePermissions, setRolePermissions] = useState<Record<string, ModulePermission[]>>({});
  const [hasChanges, setHasChanges] = useState(false);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [newRoleName, setNewRoleName] = useState("");
  const [newRoleDesc, setNewRoleDesc] = useState("");
  const [newRolePermissions, setNewRolePermissions] = useState<ModulePermission[]>([]);

  // Modal para Editar Nome & Descrição do Grupo selecionado
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editRoleName, setEditRoleName] = useState("");
  const [editRoleDesc, setEditRoleDesc] = useState("");

  // Sincroniza permissões locais ao carregar/receber grupos de fora
  useEffect(() => {
    const initialPermsMap: Record<string, ModulePermission[]> = {};
    allRoles.forEach((role) => {
      initialPermsMap[role.id] = ALL_SYSTEM_MODULES.map((m) => {
        const existing = role.permissions?.find((p) => p.moduleKey === m.key);
        return {
          moduleKey: m.key,
          moduleName: m.name,
          canView: existing ? existing.canView : true,
          canCreate: existing ? existing.canCreate : role.id === "role-admin",
          canEdit: existing ? existing.canEdit : role.id === "role-admin",
          canDelete: existing ? existing.canDelete : role.id === "role-admin",
        };
      });
    });
    setRolePermissions(initialPermsMap);
    setHasChanges(false);
  }, [roles]);

  const currentRole = allRoles.find((r) => r.id === selectedRoleId) || allRoles[0] || DEFAULT_SYSTEM_ROLES[0];
  const currentPermissions = rolePermissions[currentRole.id] || ALL_SYSTEM_MODULES.map((m) => ({
    moduleKey: m.key,
    moduleName: m.name,
    canView: true,
    canCreate: true,
    canEdit: true,
    canDelete: true,
  }));

  const handleTogglePermission = (moduleKey: string, field: "canView" | "canCreate" | "canEdit" | "canDelete") => {
    if (currentRole.isSystemDefault) return; // Grupo padrão do sistema é protegido contra edição direta rápida sem desbloquear

    setRolePermissions((prev) => {
      const currentList = prev[currentRole.id] || [];
      const updatedList = currentList.map((p) => {
        if (p.moduleKey !== moduleKey) return p;

        const updated = { ...p, [field]: !p[field] };

        // Se desmarcar visualização, desmarca as demais ações
        if (field === "canView" && !updated.canView) {
          updated.canCreate = false;
          updated.canEdit = false;
          updated.canDelete = false;
        }

        // Se marcar qualquer outra ação, força visualização como true
        if (field !== "canView" && updated[field]) {
          updated.canView = true;
        }

        return updated;
      });

      return { ...prev, [currentRole.id]: updatedList };
    });

    setHasChanges(true);
  };

  const handleToggleAllModule = (moduleKey: string, value: boolean) => {
    if (currentRole.isSystemDefault) return;

    setRolePermissions((prev) => {
      const currentList = prev[currentRole.id] || [];
      const updatedList = currentList.map((p) => {
        if (p.moduleKey !== moduleKey) return p;
        return {
          ...p,
          canView: value,
          canCreate: value,
          canEdit: value,
          canDelete: value,
        };
      });

      return { ...prev, [currentRole.id]: updatedList };
    });

    setHasChanges(true);
  };

  const handleSaveChanges = async () => {
    if (!onUpdateRole || currentRole.isSystemDefault) return;

    await onUpdateRole(currentRole.id, {
      permissions: rolePermissions[currentRole.id],
    });

    setHasChanges(false);
  };

  const handleOpenEditModal = (role: RoleGroup, e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedRoleId(role.id);
    setEditRoleName(role.name);
    setEditRoleDesc(role.description || "");
    setIsEditModalOpen(true);
  };

  const handleEditRoleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!onUpdateRole || !editRoleName.trim()) return;

    await onUpdateRole(currentRole.id, {
      name: editRoleName,
      description: editRoleDesc,
    });

    setIsEditModalOpen(false);
  };

  const handleResetToDefaults = async () => {
    if (!onResetRoles) return;
    if (confirm("Tem certeza que deseja restaurar todos os Grupos de Acesso para os módulos padrões de fábrica?")) {
      await onResetRoles();
    }
  };

  const handleOpenModal = () => {
    setNewRoleName("");
    setNewRoleDesc("");
    setNewRolePermissions(
      ALL_SYSTEM_MODULES.map((m) => ({
        moduleKey: m.key,
        moduleName: m.name,
        canView: true,
        canCreate: true,
        canEdit: true,
        canDelete: false,
      }))
    );
    setIsModalOpen(true);
  };

  const handleToggleNewRolePerm = (moduleKey: string, field: "canView" | "canCreate" | "canEdit" | "canDelete") => {
    setNewRolePermissions((prev) =>
      prev.map((p) => {
        if (p.moduleKey !== moduleKey) return p;
        const updated = { ...p, [field]: !p[field] };
        if (field === "canView" && !updated.canView) {
          updated.canCreate = false;
          updated.canEdit = false;
          updated.canDelete = false;
        }
        if (field !== "canView" && updated[field]) {
          updated.canView = true;
        }
        return updated;
      })
    );
  };

  const handleCreateRoleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newRoleName.trim()) return;

    const created = await onCreateRole({
      name: newRoleName,
      description: newRoleDesc,
      permissions: newRolePermissions,
    });

    if (created?.id) {
      setSelectedRoleId(created.id);
    }

    setIsModalOpen(false);
    setNewRoleName("");
    setNewRoleDesc("");
  };

  const handleDeleteCurrentRole = async () => {
    if (!onDeleteRole || currentRole.isSystemDefault) return;
    if (!confirm(`Deseja realmente excluir o grupo "${currentRole.name}"?`)) return;

    await onDeleteRole(currentRole.id);
    const nextRole = allRoles.find((r) => r.id !== currentRole.id);
    if (nextRole) {
      setSelectedRoleId(nextRole.id);
    }
  };

  return (
    <Card className="p-6 shadow-xs border space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4 border-b pb-4">
        <div>
          <h2 className="text-lg font-bold text-foreground flex items-center gap-2">
            <Shield className="h-5 w-5 text-primary" /> Grupos de Acesso & Matriz de Permissões
          </h2>
          <p className="text-xs text-muted-foreground">
            Defina o que cada perfil/grupo pode acessar, criar, editar ou excluir em todos os módulos do ERP.
          </p>
        </div>
        <div className="flex items-center gap-2">
          {onResetRoles && (
            <Button variant="secondary" onClick={handleResetToDefaults} disabled={isSaving} title="Restaurar grupos padrão de fábrica">
              <RefreshCw className="mr-1.5 h-4 w-4" /> Resetar Padrão
            </Button>
          )}
          <Button onClick={handleOpenModal} className="shadow-xs">
            <Plus className="mr-1.5 h-4 w-4" /> Novo Grupo de Acesso
          </Button>
        </div>
      </div>

      {/* Lista de Grupos de Acesso */}
      <div className="grid gap-4 sm:grid-cols-3">
        {allRoles.map((role) => (
          <div
            key={role.id}
            onClick={() => setSelectedRoleId(role.id)}
            className={`cursor-pointer rounded-xl border p-4 transition-all relative group ${
              selectedRoleId === role.id
                ? "border-primary bg-primary/5 ring-2 ring-primary/20 shadow-sm"
                : "bg-card hover:bg-muted/40"
            }`}
          >
            <div className="flex items-center justify-between">
              <span className="font-bold text-sm text-foreground flex items-center gap-1.5">
                <Shield className="h-4 w-4 text-primary" /> {role.name}
              </span>
              <div className="flex items-center gap-1.5">
                {role.isSystemDefault ? (
                  <Badge tone="blue">Padrão</Badge>
                ) : (
                  <Badge tone="neutral">Personalizado</Badge>
                )}
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-6 w-6 opacity-80 group-hover:opacity-100 hover:bg-primary/10"
                  onClick={(e) => handleOpenEditModal(role, e)}
                  title="Editar dados do Grupo"
                >
                  <Edit2 className="h-3.5 w-3.5 text-muted-foreground hover:text-primary" />
                </Button>
              </div>
            </div>
            <p className="mt-2 text-xs text-muted-foreground line-clamp-2">
              {role.description || "Sem descrição."}
            </p>
          </div>
        ))}
      </div>

      {/* Matriz de Permissões dos Módulos */}
      <div className="space-y-3 border-t pt-4">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <div>
            <h3 className="text-sm font-bold text-foreground flex items-center gap-2">
              Matriz de Permissões para: <span className="text-primary">{currentRole.name}</span>
              {currentRole.isSystemDefault && (
                <span className="text-[11px] font-normal text-muted-foreground flex items-center gap-1 bg-muted px-2 py-0.5 rounded-md">
                  <Lock className="h-3 w-3" /> Grupo protegido (Acesso Total)
                </span>
              )}
            </h3>
            <p className="text-xs text-muted-foreground">
              {currentRole.isSystemDefault
                ? "Este grupo é o padrão do sistema com acesso total a todas as rotas."
                : "Marque ou desmarque as permissões de cada módulo e salve as alterações."}
            </p>
          </div>

          <div className="flex items-center gap-2">
            {!currentRole.isSystemDefault && onDeleteRole && (
              <Button
                variant="ghost"
                size="sm"
                onClick={handleDeleteCurrentRole}
                className="text-xs text-rose-600 hover:text-rose-700 hover:bg-rose-50 dark:hover:bg-rose-950/30"
              >
                <Trash2 className="mr-1.5 h-3.5 w-3.5" /> Excluir Grupo
              </Button>
            )}

            {!currentRole.isSystemDefault && onUpdateRole && (
              <Button
                onClick={handleSaveChanges}
                disabled={isSaving || !hasChanges}
                size="sm"
                className="shadow-xs"
              >
                {isSaving ? (
                  <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
                ) : (
                  <Save className="mr-1.5 h-3.5 w-3.5" />
                )}
                {hasChanges ? "Salvar Permissões" : "Salvo"}
              </Button>
            )}
          </div>
        </div>

        <div className="overflow-x-auto rounded-lg border bg-card">
          <table className="w-full min-w-[700px] text-left text-xs">
            <thead className="bg-muted/60 uppercase font-semibold text-muted-foreground">
              <tr>
                <th className="px-4 py-3">Módulo do Sistema</th>
                <th className="px-4 py-3 text-center">Visualizar</th>
                <th className="px-4 py-3 text-center">Criar / Cadastrar</th>
                <th className="px-4 py-3 text-center">Editar / Alterar</th>
                <th className="px-4 py-3 text-center">Excluir / Deletar</th>
                <th className="px-4 py-3 text-center w-28">Ação Rápida</th>
              </tr>
            </thead>
            <tbody className="divide-y">
              {ALL_SYSTEM_MODULES.map((module) => {
                const perm = currentPermissions.find((p) => p.moduleKey === module.key) || {
                  moduleKey: module.key,
                  moduleName: module.name,
                  canView: true,
                  canCreate: true,
                  canEdit: true,
                  canDelete: true,
                };

                const allChecked = perm.canView && perm.canCreate && perm.canEdit && perm.canDelete;

                return (
                  <tr key={module.key} className="hover:bg-muted/30 transition-colors">
                    <td className="px-4 py-3 font-semibold text-foreground">
                      {module.name}
                    </td>
                    <td className="px-4 py-3 text-center">
                      <input
                        type="checkbox"
                        checked={perm.canView}
                        disabled={currentRole.isSystemDefault}
                        onChange={() => handleTogglePermission(module.key, "canView")}
                        className="h-4 w-4 accent-primary rounded cursor-pointer disabled:cursor-not-allowed"
                      />
                    </td>
                    <td className="px-4 py-3 text-center">
                      <input
                        type="checkbox"
                        checked={perm.canCreate}
                        disabled={currentRole.isSystemDefault}
                        onChange={() => handleTogglePermission(module.key, "canCreate")}
                        className="h-4 w-4 accent-primary rounded cursor-pointer disabled:cursor-not-allowed"
                      />
                    </td>
                    <td className="px-4 py-3 text-center">
                      <input
                        type="checkbox"
                        checked={perm.canEdit}
                        disabled={currentRole.isSystemDefault}
                        onChange={() => handleTogglePermission(module.key, "canEdit")}
                        className="h-4 w-4 accent-primary rounded cursor-pointer disabled:cursor-not-allowed"
                      />
                    </td>
                    <td className="px-4 py-3 text-center">
                      <input
                        type="checkbox"
                        checked={perm.canDelete}
                        disabled={currentRole.isSystemDefault}
                        onChange={() => handleTogglePermission(module.key, "canDelete")}
                        className="h-4 w-4 accent-primary rounded cursor-pointer disabled:cursor-not-allowed"
                      />
                    </td>
                    <td className="px-4 py-3 text-center">
                      {!currentRole.isSystemDefault && (
                        <button
                          type="button"
                          onClick={() => handleToggleAllModule(module.key, !allChecked)}
                          className="text-[11px] font-medium text-primary hover:underline"
                        >
                          {allChecked ? "Desmarcar tudo" : "Marcar tudo"}
                        </button>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal para Criar Novo Grupo */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-xs">
          <Card className="w-full max-w-2xl max-h-[90vh] overflow-y-auto p-6 shadow-2xl space-y-4">
            <div className="flex items-center justify-between border-b pb-3">
              <h3 className="text-lg font-bold flex items-center gap-2">
                <Shield className="h-5 w-5 text-primary" /> Novo Grupo de Acesso
              </h3>
              <Button variant="ghost" size="icon" onClick={() => setIsModalOpen(false)}>
                <X className="h-5 w-5" />
              </Button>
            </div>

            <form onSubmit={handleCreateRoleSubmit} className="space-y-4">
              <div className="grid gap-4 sm:grid-cols-2">
                <div>
                  <label className="mb-1 block text-xs font-semibold">Nome do Grupo *</label>
                  <Input
                    value={newRoleName}
                    onChange={(e) => setNewRoleName(e.target.value)}
                    placeholder="Ex: Operador de Vendas"
                    required
                  />
                </div>

                <div>
                  <label className="mb-1 block text-xs font-semibold">Descrição do Perfil</label>
                  <Input
                    value={newRoleDesc}
                    onChange={(e) => setNewRoleDesc(e.target.value)}
                    placeholder="Descrição das responsabilidades"
                  />
                </div>
              </div>

              <div>
                <label className="mb-2 block text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                  Permissões Iniciais dos Módulos
                </label>
                <div className="rounded-lg border overflow-x-auto max-h-60 overflow-y-auto">
                  <table className="w-full text-left text-xs">
                    <thead className="bg-muted/60 uppercase font-semibold text-muted-foreground sticky top-0 bg-muted">
                      <tr>
                        <th className="px-3 py-2">Módulo</th>
                        <th className="px-3 py-2 text-center">Ver</th>
                        <th className="px-3 py-2 text-center">Criar</th>
                        <th className="px-3 py-2 text-center">Editar</th>
                        <th className="px-3 py-2 text-center">Excluir</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {newRolePermissions.map((perm) => (
                        <tr key={perm.moduleKey}>
                          <td className="px-3 py-2 font-medium">{perm.moduleName}</td>
                          <td className="px-3 py-2 text-center">
                            <input
                              type="checkbox"
                              checked={perm.canView}
                              onChange={() => handleToggleNewRolePerm(perm.moduleKey, "canView")}
                              className="accent-primary rounded h-4 w-4 cursor-pointer"
                            />
                          </td>
                          <td className="px-3 py-2 text-center">
                            <input
                              type="checkbox"
                              checked={perm.canCreate}
                              onChange={() => handleToggleNewRolePerm(perm.moduleKey, "canCreate")}
                              className="accent-primary rounded h-4 w-4 cursor-pointer"
                            />
                          </td>
                          <td className="px-3 py-2 text-center">
                            <input
                              type="checkbox"
                              checked={perm.canEdit}
                              onChange={() => handleToggleNewRolePerm(perm.moduleKey, "canEdit")}
                              className="accent-primary rounded h-4 w-4 cursor-pointer"
                            />
                          </td>
                          <td className="px-3 py-2 text-center">
                            <input
                              type="checkbox"
                              checked={perm.canDelete}
                              onChange={() => handleToggleNewRolePerm(perm.moduleKey, "canDelete")}
                              className="accent-primary rounded h-4 w-4 cursor-pointer"
                            />
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              <div className="flex justify-end gap-2 border-t pt-4">
                <Button type="button" variant="secondary" onClick={() => setIsModalOpen(false)}>
                  Cancelar
                </Button>
                <Button type="submit" disabled={isSaving || !newRoleName.trim()}>
                  {isSaving && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />}
                  <CheckCircle2 className="mr-1.5 h-4 w-4" /> Criar Grupo
                </Button>
              </div>
            </form>
          </Card>
        </div>
      )}

      {/* Modal para Editar Nome & Descrição do Grupo */}
      {isEditModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-xs">
          <Card className="w-full max-w-md p-6 shadow-2xl space-y-4">
            <div className="flex items-center justify-between border-b pb-3">
              <h3 className="text-lg font-bold flex items-center gap-2">
                <Edit2 className="h-5 w-5 text-primary" /> Editar Grupo de Acesso
              </h3>
              <Button variant="ghost" size="icon" onClick={() => setIsEditModalOpen(false)}>
                <X className="h-5 w-5" />
              </Button>
            </div>

            <form onSubmit={handleEditRoleSubmit} className="space-y-4">
              <div>
                <label className="mb-1 block text-xs font-semibold">Nome do Grupo *</label>
                <Input
                  value={editRoleName}
                  onChange={(e) => setEditRoleName(e.target.value)}
                  placeholder="Ex: Gestor Financeiro"
                  required
                />
              </div>

              <div>
                <label className="mb-1 block text-xs font-semibold">Descrição do Perfil</label>
                <Input
                  value={editRoleDesc}
                  onChange={(e) => setEditRoleDesc(e.target.value)}
                  placeholder="Descrição das responsabilidades"
                />
              </div>

              <div className="flex justify-end gap-2 border-t pt-4">
                <Button type="button" variant="secondary" onClick={() => setIsEditModalOpen(false)}>
                  Cancelar
                </Button>
                <Button type="submit" disabled={isSaving || !editRoleName.trim()}>
                  {isSaving && <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />}
                  <CheckCircle2 className="mr-1.5 h-4 w-4" /> Salvar Alterações
                </Button>
              </div>
            </form>
          </Card>
        </div>
      )}
    </Card>
  );
}


