import { useState } from 'react';
import { Plus, Search, Edit, Trash2, MoreVertical } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { DataTable } from '@/components/common/DataTable';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useRoles } from '@/hooks/useRoles';
import { RoleDTO } from '@/types/backend';
import { RoleFormModal } from '../components/RoleFormModal';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { useToast } from '@/hooks/use-toast';

export function RolesPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedRole, setSelectedRole] = useState<RoleDTO | null>(null);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const { toast } = useToast();

  const {
    roles,
    loading,
    error,
    page,
    totalPages,
    totalElements,
    refetch,
    setPage,
    createRole,
    updateRole,
    deleteRole,
  } = useRoles({
    page: 0,
    size: 20,
    sortBy: 'code',
    sortDirection: 'ASC',
  });

  const filteredRoles = roles.filter(
    (role) =>
      role.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      role.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      (role.description?.toLowerCase().includes(searchTerm.toLowerCase()) ?? false)
  );

  const handleCreate = () => {
    setSelectedRole(null);
    setIsFormOpen(true);
  };

  const handleEdit = (role: RoleDTO) => {
    setSelectedRole(role);
    setIsFormOpen(true);
  };

  const handleDelete = (role: RoleDTO) => {
    setSelectedRole(role);
    setIsDeleteOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!selectedRole) return;
    
    try {
      await deleteRole(selectedRole.id);
      toast({
        title: 'Sucesso',
        description: 'Perfil excluído com sucesso',
      });
      setIsDeleteOpen(false);
      setSelectedRole(null);
    } catch (err: any) {
      toast({
        title: 'Erro',
        description: err.message || 'Erro ao excluir perfil',
        variant: 'destructive',
      });
    }
  };

  const handleFormSubmit = async (data: any) => {
    try {
      if (selectedRole) {
        await updateRole(selectedRole.id, data);
        toast({
          title: 'Sucesso',
          description: 'Perfil atualizado com sucesso',
        });
      } else {
        await createRole(data);
        toast({
          title: 'Sucesso',
          description: 'Perfil criado com sucesso',
        });
      }
      setIsFormOpen(false);
      setSelectedRole(null);
    } catch (err: any) {
      toast({
        title: 'Erro',
        description: err.message || 'Erro ao salvar perfil',
        variant: 'destructive',
      });
    }
  };

  const columns = [
    {
      key: 'code',
      header: 'Código',
      cell: (role: RoleDTO) => (
        <div className="font-mono font-medium">{role.code}</div>
      ),
    },
    {
      key: 'name',
      header: 'Nome',
      cell: (role: RoleDTO) => role.name,
    },
    {
      key: 'description',
      header: 'Descrição',
      cell: (role: RoleDTO) => (
        <span className="text-sm text-muted-foreground">
          {role.description || '-'}
        </span>
      ),
    },
    {
      key: 'actions',
      header: 'Ações',
      cell: (role: RoleDTO) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="sm">
              <MoreVertical className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => handleEdit(role)}>
              <Edit className="mr-2 h-4 w-4" />
              Editar
            </DropdownMenuItem>
            <DropdownMenuItem
              onClick={() => handleDelete(role)}
              className="text-destructive"
            >
              <Trash2 className="mr-2 h-4 w-4" />
              Excluir
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Gestão de Perfis"
        description="Gerir perfis e permissões do sistema"
      />

      <div className="flex items-center justify-between gap-4">
        <div className="flex-1 max-w-sm">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Pesquisar por código ou nome..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9"
            />
          </div>
        </div>
        <Button onClick={handleCreate}>
          <Plus className="mr-2 h-4 w-4" />
          Novo Perfil
        </Button>
      </div>

      {error && (
        <div className="gov-card p-4 text-destructive">
          {error}
        </div>
      )}
      <DataTable
        data={filteredRoles}
        columns={columns}
        isLoading={loading}
        emptyMessage="Nenhum perfil encontrado"
        pageSize={20}
      />

      <RoleFormModal
        open={isFormOpen}
        onOpenChange={setIsFormOpen}
        role={selectedRole}
        onSubmit={handleFormSubmit}
      />

      <ConfirmDialog
        open={isDeleteOpen}
        onOpenChange={setIsDeleteOpen}
        title="Excluir Perfil"
        description={`Tem certeza que deseja excluir o perfil "${selectedRole?.name}"? Esta ação não pode ser desfeita.`}
        onConfirm={handleDeleteConfirm}
      />
    </div>
  );
}

