import { useState } from 'react';
import { Plus, Search, Edit, Trash2, Shield, MoreVertical } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { ServerDataTable } from '@/components/common/ServerDataTable';
import { StatusBadge } from '@/components/common/StatusBadge';
import { AdvancedFilters, FilterConfig } from '@/components/common/AdvancedFilters';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useUsers } from '@/hooks/useUsers';
import { UserAccountDTO } from '@/types/backend';
import { formatDateTime } from '@/utils/locale';
import { exportToCSV } from '@/utils/export';
import { useAuth } from '@/contexts/AuthContext';
import { hasPermission } from '@/utils/permissions';
import { UserFormModal } from '../components/UserFormModal';
import { AssignRolesModal } from '../components/AssignRolesModal';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { useToast } from '@/hooks/use-toast';

export function UsersPage() {
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [selectedUser, setSelectedUser] = useState<UserAccountDTO | null>(null);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [isRolesOpen, setIsRolesOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const { toast } = useToast();
  const { user } = useAuth();

  const canCreate = user && hasPermission(user.roles, 'admin.users.create');
  const canEdit = user && hasPermission(user.roles, 'admin.users.edit');
  const canDelete = user && hasPermission(user.roles, 'admin.users.delete');

  const {
    users,
    loading,
    error,
    page,
    totalPages,
    totalElements,
    refetch,
    setPage,
    createUser,
    updateUser,
    deleteUser,
  } = useUsers({
    page: 0,
    size: 20,
    sortBy: 'createdAt',
    sortDirection: 'DESC',
  });

  // Filtrar usuários localmente
  const filteredUsers = users.filter((user) => {
    const matchesSearch =
      user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.fullName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.email.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesStatus = !statusFilter ||
      (statusFilter === 'active' && user.isActive) ||
      (statusFilter === 'inactive' && !user.isActive);

    return matchesSearch && matchesStatus;
  });

  const filterConfigs: FilterConfig[] = [
    {
      key: 'status',
      label: 'Estado',
      type: 'select',
      options: [
        { value: 'active', label: 'Activo' },
        { value: 'inactive', label: 'Inactivo' },
      ],
    },
  ];

  const filterValues = {
    status: statusFilter,
  };

  const handleFilterChange = (key: string, value: any) => {
    if (key === 'status') {
      setStatusFilter(value);
    }
  };

  const handleFilterReset = () => {
    setStatusFilter('');
  };

  const handleExport = () => {
    const headers: Record<string, string> = {
      username: 'Username',
      fullName: 'Nome Completo',
      email: 'Email',
      isActive: 'Estado',
      roleIds: 'Perfis',
      createdAt: 'Criado em',
    };
    exportToCSV(filteredUsers, 'utilizadores', headers);
    toast({
      title: 'Exportação concluída',
      description: 'Os dados foram exportados para CSV',
    });
  };

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

  const handleEdit = (user: UserAccountDTO) => {
    setSelectedUser(user);
    setIsFormOpen(true);
  };

  const handleAssignRoles = (user: UserAccountDTO) => {
    setSelectedUser(user);
    setIsRolesOpen(true);
  };

  const handleDelete = (user: UserAccountDTO) => {
    setSelectedUser(user);
    setIsDeleteOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!selectedUser) return;

    try {
      await deleteUser(selectedUser.id);
      toast({
        title: 'Sucesso',
        description: 'Utilizador excluído com sucesso',
      });
      setIsDeleteOpen(false);
      setSelectedUser(null);
    } catch (err: any) {
      toast({
        title: 'Erro',
        description: err.message || 'Erro ao excluir utilizador',
        variant: 'destructive',
      });
    }
  };

  const handleFormSubmit = async (data: any) => {
    try {
      if (selectedUser) {
        await updateUser(selectedUser.id, data);
        toast({
          title: 'Sucesso',
          description: 'Utilizador atualizado com sucesso',
        });
      } else {
        await createUser(data);
        toast({
          title: 'Sucesso',
          description: 'Utilizador criado com sucesso',
        });
      }
      setIsFormOpen(false);
      setSelectedUser(null);
    } catch (err: any) {
      toast({
        title: 'Erro',
        description: err.message || 'Erro ao salvar utilizador',
        variant: 'destructive',
      });
    }
  };

  const columns = [
    {
      key: 'username',
      header: 'Username',
      cell: (user: UserAccountDTO) => (
        <div>
          <div className="font-medium">{user.username}</div>
          <div className="text-sm text-muted-foreground">{user.email}</div>
        </div>
      ),
    },
    {
      key: 'fullName',
      header: 'Nome Completo',
      cell: (user: UserAccountDTO) => user.fullName,
    },
    {
      key: 'isActive',
      header: 'Estado',
      cell: (user: UserAccountDTO) => (
        <StatusBadge status={user.isActive ? 'active' : 'inactive'} />
      ),
    },
    {
      key: 'roleIds',
      header: 'Perfis',
      cell: (user: UserAccountDTO) => (
        <span className="text-sm text-muted-foreground">
          {user.roleIds?.length || 0} perfil(is)
        </span>
      ),
    },
    {
      key: 'createdAt',
      header: 'Criado em',
      cell: (user: UserAccountDTO) => formatDateTime(user.createdAt),
    },
    {
      key: 'actions',
      header: 'Ações',
      cell: (user: UserAccountDTO) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="sm">
              <MoreVertical className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {canEdit && (
              <DropdownMenuItem onClick={() => handleEdit(user)}>
                <Edit className="mr-2 h-4 w-4" />
                Editar
              </DropdownMenuItem>
            )}
            <DropdownMenuItem onClick={() => handleAssignRoles(user)}>
              <Shield className="mr-2 h-4 w-4" />
              Atribuir Perfis
            </DropdownMenuItem>
            {canDelete && (
              <DropdownMenuItem
                onClick={() => handleDelete(user)}
                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 Utilizadores"
        description="Gerir contas de utilizadores, perfis e permissões do sistema"
      />

      {/* Actions Bar */}
      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-2 flex-1">
          <AdvancedFilters
            filters={filterConfigs}
            values={filterValues}
            onChange={handleFilterChange}
            onReset={handleFilterReset}
          />
        </div>
        {canCreate && (
          <Button onClick={handleCreate}>
            <Plus className="mr-2 h-4 w-4" />
            Novo Utilizador
          </Button>
        )}
      </div>

      {/* Table */}
      <ServerDataTable
        data={filteredUsers}
        columns={columns}
        loading={loading}
        error={error}
        page={page}
        totalPages={totalPages}
        totalElements={totalElements}
        pageSize={20}
        onPageChange={setPage}
        onSearch={setSearchTerm}
        searchPlaceholder="Pesquisar por username, nome ou email..."
        emptyMessage="Nenhum utilizador encontrado"
        onExport={handleExport}
        exportLabel="Exportar CSV"
      />

      {/* Modals */}
      <UserFormModal
        open={isFormOpen}
        onOpenChange={setIsFormOpen}
        user={selectedUser}
        onSubmit={handleFormSubmit}
      />

      <AssignRolesModal
        open={isRolesOpen}
        onOpenChange={setIsRolesOpen}
        user={selectedUser}
        onSuccess={() => {
          setIsRolesOpen(false);
          refetch();
        }}
      />

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

